Course contentsShow
← Web Development
Lesson 1494 of 2,98227. REST API Design for FrontendFree lesson

Status Code Response Bodies

Learn what data to expect in response bodies for different status codes and error formats.

Status Code Response Bodies

You'll learn what data to include in your API's response bodies for different HTTP status codes and how to format error messages consistently.

The Core Idea

When your API sends back a status code, the response body should match what that code promises. A 200 OK should contain the requested data. A 404 Not Found should explain what wasn't found. A 500 Internal Server Error shouldn't leak sensitive details. Think of it like a package delivery: the status code is the tracking status ("delivered," "failed"), and the response body is what's actually inside the box—it should match expectations.

Success Response Bodies (2xx)

For successful requests, return the relevant data:

  • 200 OK: The full resource or list of resources
  • 201 Created: The newly created resource, often with its new ID and location
  • 204 No Content: Literally nothing—the body should be empty

Error Response Bodies (4xx and 5xx)

Error responses need helpful information. A consistent format helps frontend developers handle errors predictably:

{
  "error": {
    "code": "RESOURCE_NOT_FOUND",
    "message": "User with ID 12345 does not exist",
    "statusCode": 404
  }
}

Common patterns include:

  • A human-readable message for developers or users
  • A machine-readable error code for programmatic handling
  • Field-specific errors for validation failures (422)
  • No sensitive details in 5xx errors—just "Internal Server Error" and a tracking ID

What to Avoid

Never return HTML error pages from a JSON API. Don't expose stack traces or database errors to clients. Keep 5xx responses vague externally but log details internally.

Key Takeaway: Match your response body content to your status code—data for success, structured error details for failures, and always maintain a consistent format your frontend can rely on.