HTTP headers – REST APIs
REST APIs leverage HTTP headers to transmit clients’ information and describe their options and capabilities. Headers are part of both the request and the response.One well-known header is the Location header, that we use for different purposes. For example:
- After creating an entity (201 Created), the Location header should point to the GET endpoint where the client can access that new entity.
- After starting an asynchronous operation (202 Accepted), the Location header could point to the status endpoint where you can poll for the state of the operation (has it completed, failed, or is it still ongoing).
- When a server wants to instruct a client to load another page (a redirection), the Location header contains the destination URL. The following status codes are the most common for redirections: 301 Moved Permanently, 302 Found, 303 See Other, 307 Temporary Redirect, and 308 Permanent Redirect.
The Retry-After header can also come in handy when mixed with 202 Accepted, 301 Moved Permanently, 429 Too Many Requests, or 503 Service Unavailable. The ETag header identifies the version of the entity and can be used in conjunction with If-Match to avoid mid-air collisions. The ETag and If-Match headers form a sort of optimistic concurrency method that prevents request two from overwriting changes made by request one when changes are happening simultaneously or not in the expected order; a.k.a. a way to manage conflicts. We can also add the following to the mix as an example of HTTP headers that describe a REST endpoint: Allow, Authorization, and Cache-Control. The list is very long, and it would help no one to enumerate all HTTP headers here.
This information should be enough theory to get you started with HTTP and REST. In case you want to know more, I left links to the MDN web docs about HTTP in the Further Reading section at the end of the chapter.
Versioning is a crucial aspect of a REST API. Whether the version of the API is long-lived or transitory (during the decommissioning cycle of an old endpoint, for example), both ends of the pipe must know what to expect; what API contract to respect. Unless you are your only consumer, you’ll need a way for the API clients to query specific API versions when the contract changes.This section explores a few ways to think about our versioning strategy.