Content negotiation

Content negotiation is how one URL can serve several representations. The client states what it can accept; the server picks from what it can produce; the response says which was chosen. The resource is the same either way — only its rendering differs.

How it works

The client sends Accept with the media types it wants, optionally weighted with q-values. The server replies with Content-Type naming what it actually sent, and should send Vary: Accept so caches do not serve a JSON response to a client that asked for CSV. If nothing the client will accept can be produced, the answer is 406 Not Acceptable. The mirror case — the client sending a body in a type the server will not parse — is 415 Unsupported Media Type.

The misconception

That Accept is advisory and can be ignored. Many APIs do ignore it and always return JSON, which works until a client genuinely needs something else and gets JSON with a 200, silently. The honest answer to an unsatisfiable Accept header is a 406.

Try it here

The Protocol Lab negotiates for real: `GET /protocol/v1/export/documents` will produce JSON, CSV or XML depending on your Accept header, sets Content-Type to whatever it chose, and answers 406 rather than silently falling back when you ask for something it cannot make. The Friends API pairs it with a 415 on the way in.

Related

Other terms

All glossary terms · Testing techniques · All 39 mock REST APIs