Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 39 ยท HTTP and REST Fundamentals

Headers and Content Negotiation

Learn the HTTP headers every API developer needs: Content-Type, Accept, content negotiation, Cache-Control, ETag and conditional requests, CORS and custom headers.

Headers are the metadata of an HTTP message. The URL says what you want, the method says what to do, and headers say how: in which format, with which credentials, for how long the answer may be cached, from which origin. A REST API that uses headers well needs fewer special URLs and fewer custom fields in its JSON.

This lesson covers the headers you will use in almost every API and shows two of the most useful tricks, content negotiation and conditional requests, in running code.

Headers you will meet every day

Header Direction Purpose
Content-Type both Format of the body being sent
Accept request Formats the client can handle
Accept-Language request Preferred human languages
Authorization request Credentials (see Authentication Basics)
User-Agent request Name of the client software
Location response URL of a created or moved resource
Cache-Control both Caching rules
ETag / If-None-Match response / request Validators for conditional requests
Retry-After response When to try again (429, 503)
Allow response Methods the resource supports
Access-Control-Allow-Origin response CORS permission for browsers

Header names are case-insensitive. Custom headers used to start with X- (for example X-Request-Id); since RFC 6648 the X- prefix is deprecated, and a plain name like Request-Id or RateLimit-Remaining is preferred for new ones.

Content-Type and Accept

Content-Type describes the body you are sending. Accept lists the formats you are willing to receive. Together they implement content negotiation: the same URL can offer several representations of one resource.

HTTP
GET /books/42 HTTP/1.1
Accept: application/json

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

Accept can list several types with weights called quality values: Accept: application/json, text/csv;q=0.5, */*;q=0.1 means "JSON is my first choice, CSV acceptable, anything else as a last resort". If the server cannot produce any acceptable type, it answers 406 Not Acceptable. If a client sends a body in a type the server cannot read, the answer is 415 Unsupported Media Type.

Node.js Content negotiation with Accept

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The Vary: Accept header matters when a cache sits in front of your API: it tells the cache that the response depends on the Accept request header, so a CSV answer is never served to a client that asked for JSON.

Caching with Cache-Control

Cache-Control tells clients and shared caches (CDNs, proxies) how long they may reuse a response:

  • Cache-Control: no-store: never store (private data, tokens).
  • Cache-Control: private, max-age=60: only the end user's browser may cache, for 60 seconds.
  • Cache-Control: public, max-age=300: any cache may keep it for 5 minutes.
  • Cache-Control: no-cache: may store, but must revalidate with the server before each reuse.

Only GET (and HEAD) responses are cached in practice. Responses that depend on Authorization should be private or no-store unless you know exactly what you are doing.

Conditional requests with ETag

When a cached copy expires, the client does not have to download it again if nothing changed. The server attaches an ETag (an opaque version fingerprint, often a hash of the body). The client later sends it back in If-None-Match. If it still matches, the server replies 304 Not Modified with no body.

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: GET /books/42
    S-->>C: 200 + ETag "abc" + body
    C->>S: GET /books/42 + If-None-Match "abc"
    S-->>C: 304 Not Modified (no body)

A 304 saves bandwidth: only headers travel.

The same validators also protect against lost updates: PUT with If-Match: "abc" succeeds only if the resource still has that version, otherwise the server answers 412 Precondition Failed.

Node.js ETag and 304 Not Modified

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

CORS in a nutshell

Browsers block JavaScript on https://app.example.com from reading responses from https://api.example.com unless the API opts in with CORS headers. The simplest opt-in is Access-Control-Allow-Origin: https://app.example.com. For requests with custom headers or methods such as PUT, the browser first sends an OPTIONS preflight, and the server must answer with Access-Control-Allow-Methods and Access-Control-Allow-Headers. CORS only restricts browsers, not tools like curl, so it is never a substitute for authentication. The security chapter returns to it in detail.

Other useful headers

  • Location: after 201 Created or a redirect.
  • Retry-After: seconds (or a date) until the client may retry.
  • Request-Id: a unique id per request, echoed in logs and error bodies so a user can quote it in a bug report.
  • Idempotency-Key: makes a POST safe to retry (see HTTP methods).
  • Link: pagination and relation links (<...>; rel="next").

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which header lists the formats a client is willing to receive?

    Accept is sent by the client. Content-Type describes the body that accompanies a message.
  2. 2. A client sends Accept - application/xml, but the API only offers JSON and CSV. What should it return?

    406 means the server cannot produce any representation the client accepts. 415 is for an unsupported request body.
  3. 3. What does a 304 response tell the client?

    304 Not Modified is the answer to a conditional request whose validator still matches.
  4. 4. Why add Vary - Accept to a response that depends on the Accept header?

    Without Vary, a shared cache could serve a CSV response to a client that asked for JSON.
  5. 5. Which statement about CORS is true?

    CORS is a browser rule. Anyone can call your API outside a browser, so you still need real authentication.

Summary

  • Content-Type describes the body you send; Accept says what you can receive; the server negotiates and answers 406 or 415 when it cannot comply.
  • Vary: Accept keeps caches correct when the representation depends on a request header.
  • Cache-Control sets caching rules; ETag with If-None-Match gives cheap revalidation (304), and If-Match prevents lost updates (412).
  • CORS is a browser mechanism, not security by itself.
  • Prefer clear, unprefixed names for new custom headers.

Next: Resource Naming and URLs