Card 06/ 09

ConceptDifficulty: Intermediate2 min

Redirects: 301, 302, 307 and 308

Four redirect codes split on two questions, whether the move is permanent and whether the method must stay the same.

A redirect tells the client that the resource is at another URL, given in the Location header. The four common codes split on two questions: is the move permanent, so the client should use the new URL from now on, and must the client repeat the same method and body there? 307 and 308 keep the method; 301 and 302 allow a client to turn a POST into a GET.

The four redirect codes by permanence and by whether the method is kept
MoveMethod may change to GETMethod must stay the same
Permanent301 Moved Permanently308 Permanent Redirect
Temporary302 Found307 Temporary Redirect

Why the method can change. Early browsers, given a 301 or 302 after a POST, followed it with a GET and dropped the body. The behaviour became so common that the standard now allows it. For a web form that is often what was wanted; for an API it silently turns a write into a read.

Three scenarios. An endpoint renamed for good from /v1/customers to /v1/clients, called only with GET: 301 works, and clients may update stored URLs. A POST endpoint moved for good, whose clients must keep posting: 308, so the order is not lost. A service briefly sending writes to a standby while its primary is upgraded: 307, so clients keep using the original URL afterwards.

What the client should do next. Follow the Location header, with the same method for 307 and 308. Cache the new URL only for 301 and 308. Many HTTP libraries follow redirects by themselves but limit how many, and some refuse to follow one to a different host with the original credentials.

In API design. Prefer 307 and 308 whenever a write might be redirected. Better still, avoid redirecting writes at all; a client that has to resend a payment to a second URL is a client that may send it twice.

So decide first whether the move is permanent, then whether the method matters; for an API, it almost always does.