Key headers
Headers are message metadata that clients, proxies, gateways and caches act on, including Content-Type, Accept, Location, Cache-Control and Set-Cookie. A correct body with the right status does not prove the response is right: a wrong Content-Type, a missing Location or a cookie without Secure, HttpOnly and SameSite goes unnoticed. They are checked on both successful and error responses.
API · Headers
The body is right, the status is 201, yet the client cannot open the resource. What is in the headers?
After a transfer is created the API returns 201 and correct JSON, yet the mobile client opens nothing. The response has no Location, Content-Type says text/html, the X-Powered-By header shows the framework version, and the session cookie arrived without a single security attribute. None of these defects is visible in the body.
Headers are the metadata of a message. This lesson covers how they are built, which of them to check in every response, and how to catch a defect that the body hides.
How it is built
A header is a "name: value" pair placed before the message body (RFC 9110). They exist because proxies, gateways and caches sit between the client and the server, and they do not parse bodies, they act on metadata only. Headers answer four questions: what is in the body (Content-Type), what the client wants (Accept), who you are (Authorization, Cookie) and what to do next (Location, Cache-Control, Retry-After).
| Header | Where | What for |
|---|---|---|
Content-Type | Request and response | Body format, for example application/json |
Accept | Request | Which format the client wants back |
Authorization | Request | A token or credentials |
Location | Response | URL of the created resource or of a redirect |
Cache-Control | Response | Caching rules |
ETag | Response | Resource version for caching and concurrent updates |
Retry-After | Response | When to retry after 429 or 503 |
Set-Cookie | Response | A cookie with security attributes |
Format negotiation. The client says in Accept what it can read, the server says in Content-Type what it sent. If the requested format does not exist, RFC 9110 allows 406 Not Acceptable but does not require it: the server may also ignore Accept and return a default format. What a particular API does is set by its contract, so the test is written against the documentation, not against "correct" textbook behaviour.
Format negotiation
Example: a response whose body is right and headers are not
Before. The test checks status === 201 and body.id, and it is green on this response:
HTTP/1.1 201 Created
Content-Type: text/html; charset=utf-8
X-Powered-By: Express/4.17.1
Set-Cookie: sid=9f2c1e; Path=/
{ "id": "tr_91", "status": "pending" }
Read it by its headers. Content-Type: text/html for JSON: clients and proxies that trust the type will not parse the body, and a browser with nosniff refuses to treat it as a script. There is no Location, so the client does not know where to find the created resource. X-Powered-By: Express/4.17.1 tells an attacker which known vulnerabilities to look for. A cookie without Secure, HttpOnly and SameSite can be stolen by a script or intercepted over HTTP.
After. The correct response:
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Location: /v1/transfers/tr_91
Set-Cookie: sid=9f2c1e; Path=/; Secure; HttpOnly; SameSite=Lax
{ "id": "tr_91", "status": "pending" }
And a test that catches it instead of guessing:
import { test, expect } from '@playwright/test';
test('create transfer: response headers', async ({ request }) => {
const res = await request.post('/v1/transfers', {
data: { toAccount: 'UA21...', amount: 150, currency: 'UAH' },
});
expect(res.status()).toBe(201);
const h = res.headers(); // names are lower case
expect(h['content-type']).toMatch(/^application\/json/);
expect(h['location']).toMatch(/^\/v1\/transfers\/tr_\w+$/);
expect(h['x-powered-by']).toBeUndefined();
const cookies = res.headersArray().filter((x) => x.name.toLowerCase() === 'set-cookie');
for (const c of cookies) {
expect(c.value).toContain('HttpOnly');
expect(c.value).toContain('Secure');
expect(c.value).toMatch(/SameSite=(Lax|Strict)/i);
}
});
Reading headers by lower-case name is convenient here: Playwright returns headers() in lower case. Headers that repeat (Set-Cookie) need headersArray(), because the headers() object joins values into one string.
A negative case for format negotiation takes one request:
# the client asks for a format the API does not offer
curl -i "$BASE/v1/transfers/tr_91" \
-H "Authorization: Bearer $TOKEN" \
-H "Accept: application/xml"
# expected by the contract: 406 Not Acceptable, or JSON if the
# contract says "Accept is ignored". Not an HTML error page.
Limits and alternatives
- Header names are case-insensitive, while values depend on the header: media type and subtype are case-insensitive too under RFC 9110, but some clients compare
application/jsonandApplication/JSONas plain strings. Only the name is compared without case, and the type in the value is checked with a regular expression that tolerates a trailingcharset. - Some headers are added not by the API but by a proxy, gateway or CDN (
Via,X-Request-Id,Server). A defect there may be a gateway setting rather than service code, so test the same path users take. - In Postman the client itself adds some headers (
User-Agent,Postman-Token,Accept-Encoding). They are hidden on the Headers tab (the hidden toggle) and visible in the Postman console, so "works in Postman" does not mean it works without them. - A browser front end does not see all response headers: cross-origin requests need
Access-Control-Expose-Headers(see the CORS lesson). An API-level test will not show that.
Common mistakes
- Checking only the body and the status. A wrong
Content-Type, a missingLocationand cookies without flags go unnoticed and break the client or security later. - Expecting 406 by default. Not every API returns it, and a test written "by the textbook" reports a false defect. Contract first, case second.
- Comparing
content-typefor exact equality.application/json; charset=utf-8is not equal toapplication/json, and the test fails without a defect. Check the start of the string. - Not checking headers on errors. 404 and 500 also need the right
Content-Type, and that is sometimes whereX-Powered-Byleaks.
Check yourself
The API ignores Accept: application/xml and returns JSON with status 200. Is it a bug?
Answer
Not necessarily. RFC 9110 allows both 406 and returning a default format. It is a bug if the contract promises 406, or if Content-Type says application/xml while the body is JSON. Check the documentation first.
The response has Set-Cookie: sid=abc; Path=/. What is wrong and why is it dangerous?
Answer
There is no HttpOnly (a page script, including one injected through XSS, can read the session), no Secure (the cookie also travels over plain HTTP) and no SameSite (a browser that does not default to Lax sends it from other sites too, which opens the way to CSRF).
Content-Type, Location after creation, Authorization in the request and the cookie attributes. Middle/Senior: A body with the right status does not prove the response is right: the client, proxies and the browser act on headers. I check the content type with charset in mind, Location, the cookie flags and the absence of X-Powered-By, on both successful and error responses. I match the reaction to an unsupported Accept against the contract, because the RFC allows both 406 and a default format.