Headers as a negotiation
Content-Type, Accept, Accept-Encoding, ETag, Cache-Control. The conversation happening around every request you have been ignoring.
Content-Type on a request says what you sent; Accept says what you would like back. A server may support several representations of the same resource at one URL, JSON, CSV, an HTML page, and choose based on Accept. Most APIs never use this, and that is a reasonable choice, but knowing it exists explains why the header is there and why sending the wrong Content-Type produces a body-parsing error rather than a validation error.
Conditional requests are the pair worth adopting immediately. Return an ETag with a response and clients can send If-None-Match next time; if nothing changed you answer 304 with no body at all. On a list endpoint that is polled every thirty seconds this is the difference between shipping the payload two thousand times a day and shipping it when it changes.
Two headers are worth setting even on a small service. Cache-Control, because the default is ambiguous and intermediaries will make their own decisions, and a strict Content-Type with charset, because content sniffing is a genuine security issue and X-Content-Type-Options: nosniff is one line.
You should now be able to
- Read the headers of a real request and explain each one
- Serve different representations from one URL
- Use conditional requests to avoid sending unchanged bytes
Loading…