Request and Response Structure: Headers, Body, and Content Negotiation
request headers, response headers, Accept header, Content-Type, content negotiation, JSON schema, response envelope, HATEOAS
Request and Response Structure: Headers, Body, and Content Negotiation
A well-structured REST API response is as important as a well-designed URL. Clients should be able to predict the shape of your responses, handle errors consistently, and understand metadata without parsing the body. This lesson covers the anatomy of production-quality REST API requests and responses.
Essential Request Headers
Content-Type: application/json must be sent with any request that includes a body (POST, PUT, PATCH). This tells the server how to parse the body. Accept: application/json tells the server what format the client expects back. Authorization: Bearer token carries the authentication credential. X-Request-ID is a client-generated unique ID used for tracing requests through distributed systems.
Content Negotiation
Content negotiation is the mechanism by which a client and server agree on the format of the response. The client sets the Accept header; the server responds with the best available format and confirms it in the Content-Type response header. If the server cannot produce the requested format, it returns 406 Not Acceptable.
Consistent Response Structure
Production APIs use a consistent response envelope so clients always know where to find the data, metadata, and errors:
{
"success": true,
"data": {
"id": 42,
"name": "Alice Johnson"
},
"meta": {
"timestamp": "2024-01-15T10:30:00Z",
"requestId": "req_abc123"
}
}Error Response Structure
Error responses should follow the same envelope pattern with machine-readable error codes:
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "The email field is required.",
"details": [
{ "field": "email", "issue": "required" }
]
}
}HATEOAS: Hypermedia Links
HATEOAS (Hypermedia as the Engine of Application State) is an advanced REST constraint where responses include links to related actions and resources. This makes the API self-navigable. Including a self link in every response is considered a widely adopted best practice.
