Response Formatting
- REST API
- Node.js
- Express
Giving an API a consistent response structure — for both success and error — so every client can parse results and handle failures the same way.
What you'll understand
- Why a consistent response format matters across an API
- How to structure success and error responses
- How status codes and response bodies work together
Explanation
Response formatting is the practice of giving every endpoint in an API a predictable structure. When a client can rely on the same shape for every success and every error, it can write parsing and error handling once and reuse it everywhere. When each endpoint invents its own shape, clients accumulate special cases and bugs.
Two decisions define the format. First, the success shape: whether you return the resource directly or wrap it in a consistent envelope, and how you represent collections (often with their pagination details alongside). Second, the error shape: a stable structure with a machine-readable code and a human-readable message, so clients can react to failures programmatically rather than parsing prose.
Formatting works together with HTTP status codes, it does not replace them (see Related Topics). The status code is the primary signal of what happened, 200, 201, 400, 404, and the body carries the detail. A common mistake is to return 200 with an error hidden in the body; keep the status honest and let the formatted body explain.
Examples
A consistent error shape lets clients handle every failure the same way:
{
"error": {
"code": "VALIDATION_FAILED",
"message": "Email is required"
}
}A collection response pairs the data with the information a client needs to page through it:
{
"data": [ { "id": 1 }, { "id": 2 } ],
"page": 1,
"pageSize": 20,
"total": 57
}Common mistakes
- Using a different response shape for each endpoint.
- Returning 200 for errors and burying the failure in the body.
- Sending raw error strings or stack traces instead of a structured error object.
- Formatting single resources and collections inconsistently.
Best practices
- Choose one success shape and one error shape and apply them everywhere.
- Give errors a stable machine-readable code plus a readable message.
- Keep HTTP status codes accurate and let the body carry the detail (see Related Topics).
- Represent collections consistently, including their pagination metadata.
Further reading
- Microsoft, Web API design best practices — https://learn.microsoft.com/en-us/azure/architecture/best-practices/api-design
- MDN, HTTP response status codes — https://developer.mozilla.org/en-US/docs/Web/HTTP/Status