REST API headers are key-value pairs sent along with an HTTP request or response to provide metadata about the call. They allow the client and server to communicate essential details like authentication tokens, data formats, and caching rules without altering the main message body.
Many developers mistake headers for the request body. While the body contains the actual data you want to process, headers act as the envelope, telling the server how to handle that data and who is sending it.
Define the Content Type for Data Exchange
The Content-Type header is the most critical piece of metadata for any API call. It tells the receiving party exactly how to interpret the bytes in the message body. If you send a JSON string but do not specify the content type, the server may treat it as plain text or fail to parse it entirely, resulting in a 400 Bad Request or 415 Unsupported Media Type error.
For modern REST APIs, application/json is the standard. However, you may encounter other types depending on the task. When uploading a file, you use multipart/form-data. When sending a simple form, application/x-www-form-urlencoded is common. If you are sending a raw image, you might use image/png or image/jpeg.
The Accept header works as the mirror to Content-Type. While Content-Type says "this is what I am sending," Accept says "this is what I want back." For example, if you set Accept: application/json, you are instructing the server to return the response in JSON format. If the server can provide multiple formats, such as XML and JSON, it uses this header to decide which one to generate.
Secure the Connection With Authorization Headers
Authorization headers prove your identity to the server. Without these, a protected API will return a 401 Unauthorized status. The most common method for REST APIs is the Bearer Token, often used with JSON Web Tokens (JWT). This follows a specific format: Authorization: Bearer <token>.
Another common method is Basic Authentication. This uses the format Authorization: Basic <base64-encoded-credentials>. In this case, the username and password are joined by a colon and then encoded in Base64. Because Base64 is easily decoded, Basic Auth must only be used over HTTPS to prevent credentials from being intercepted in plain text.
API Keys are sometimes passed in custom headers rather than the standard Authorization header. You might see headers like X-API-Key: your_key_here. The "X-" prefix was traditionally used for non-standard, custom headers, though modern standards suggest using a descriptive name without the prefix if the header is intended for wide use.
Manage Traffic and Cache with Control Headers
Headers can prevent your application from overloading a server or wasting bandwidth. The Cache-Control header is used to determine if a response can be stored by the client or a proxy. A value of no-cache forces the client to re-validate the request with the server every time, which is essential for data that changes frequently, such as a stock price or a user's bank balance.
To limit how often a client calls an API, servers use rate-limiting headers. These are usually returned in the response to tell the client when they can try again. Common headers include X-RateLimit-Limit (the total requests allowed per window), X-RateLimit-Remaining (how many calls are left), and X-RateLimit-Reset (the time in seconds until the limit resets).
If you hit a limit, the server returns a 429 Too Many Requests status. You should check the Retry-After header in that response. This header provides a value in seconds or a specific date, telling your code exactly how long to wait before attempting the request again to avoid a permanent ban.
Implement a Worked Request Example
Consider a scenario where you need to update a user's profile email address. You are using a PUT request to a specific user endpoint. To do this correctly, you must provide the identity of the user, the format of the data, and the format you expect in return.
Your HTTP request would look like this:
PUT /api/v1/users/12345 HTTP/1.1
Host: api.example.com
Authorization: Bearer abc123xyz789
Content-Type: application/json
Accept: application/json
{
"email": "new-email@example.com"
}
In this example, the Host header identifies the server. The Authorization header provides the JWT token to prove you have permission to edit user 12345. The Content-Type tells the server the body is JSON. The Accept header ensures the server responds with a JSON confirmation of the update.
The server would then respond with headers like Content-Length: 150 (the size of the response body in bytes) and Date: Wed, 21 Oct 2023 12:00:00 GMT, followed by the updated user object in the body.
Handle Common Header Errors
When a request fails, the headers often contain the clue. A 406 Not Acceptable response means the server cannot produce a response matching the Accept header you provided. If you requested Accept: application/xml but the server only speaks JSON, this error occurs. The fix is to change your Accept header to application/json or */* (which means any format).
A 415 Unsupported Media Type error happens when the server refuses the Content-Type of your request. This often occurs when a developer sends a JSON body but forgets to set the Content-Type: application/json header. The server sees the raw text but does not know it should be parsed as JSON, so it rejects the request.
If you receive a 401 Unauthorized, check your Authorization header for typos. A common mistake is forgetting the word "Bearer" before the token or including a space where one should not be. Ensure the token is current and has not expired. If the token is expired, the server may return a 401 or a 403 Forbidden, depending on the API's security logic.
Follow a Rule of Thumb for Header Design
When designing your own API headers, follow the rule of "Standard First, Custom Last." Always use the official HTTP standard headers for common tasks. Use Authorization for security, Content-Type for formats, and Cache-Control for caching. Only create custom headers when the standard ones cannot describe the specific metadata you need.
Keep your header names consistent across all endpoints. If you use X-Request-ID to track a request through your logs in one endpoint, use it in every other endpoint. This makes debugging significantly easier because you can trace a single ID across multiple services in your backend logs. Always ensure your server handles missing headers gracefully by providing a sensible default or a clear error message to the client.