Card 02/ 10
Representations: JSON, Content-Type and Accept
The server stores an order one way and sends it another, and two headers say which format is on the wire.
A representation is one format of a resource sent over HTTP, such as an order written as JSON. Two headers name the format: Content-Type says what the body of this message is, and Accept says what the client wants back. When they do not match what the server can handle, it answers 415 Unsupported Media Type for a body it cannot read, or 406 Not Acceptable for a format it cannot produce.
POST /orders HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json
{"items":[{"sku":"pen-blue","quantity":3}]}
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Location: /orders/43
{"id":"43","status":"open","items":[{"sku":"pen-blue","quantity":3}]}Content-Type travels on any message with a body, request or response. application/json is a media type: a registered name for a format. Without the header, the receiver has to guess, and some frameworks will refuse to parse the body at all.
Accept travels on the request and lists the formats the client can read, optionally with preferences, such as Accept: application/json, text/csv;q=0.5. Choosing the response format from it is called content negotiation. Most APIs offer only JSON, and should still answer 406 rather than send something the client said it cannot read.
Serialising is turning the server's internal object into the bytes of a representation; parsing is the reverse. The internal object and the representation need not have the same fields, and usually should not.
Versioned media types. Some APIs put the version in the media type, such as application/vnd.example.v2+json. That works, and it is one of several ways to version an API.
So send Content-Type on every body, honour Accept, and answer with 415 or 406 when the format is wrong rather than failing somewhere deeper.
← → move through sections and cards