Card 03/ 09

ConceptDifficulty: Beginner2 min

Client Error Codes: 400, 404, 409, 422 and 429

A 4xx says the request was wrong, and which code says how the client can fix it.

The 4xx class says the request was wrong, and the client must change something before trying again. Each code points at a different fix: 400 means the request could not be understood, 404 means the resource does not exist, 409 means it conflicts with the current state, 422 means it was understood but the values are not acceptable, and 429 means the client is sending too many requests.

Five client error codes, with a request that earns each and the fix
CodeScenarioRequest excerptClient's fix
400 Bad RequestThe body is not valid JSON{"sku": "pen-blue",Send well-formed JSON
404 Not FoundThe order does not existGET /orders/99999Check the id; do not retry
409 ConflictAn account with that email already existsPOST /users {"email": "[email protected]"}Use another email, or sign in
422 Unprocessable ContentValid JSON, but the delivery date is in the past{"deliverOn": "2020-01-01"}Correct the value
429 Too Many RequestsThe client exceeded its rate limitThe 101st request this minuteWait for the time in Retry-After

400 or 422. Both say the request was wrong. Use 400 when the server cannot read it at all: broken JSON, a missing required header, a query parameter of the wrong type. Use 422 when it read the request fine and the values break a rule: a date in the past, a quantity of zero. Many APIs use 400 for both, which is allowed; using 422 for the second case tells the client the format is right and only the data needs fixing.

409 is for a request that would be fine on its own but clashes with what the server holds now: a duplicate unique value, or an update to a record someone else changed first.

404 says nothing exists at that URL. A server may also send it to hide that something exists from a caller who may not see it.

429 is the one 4xx a client should retry unchanged, once it has waited. The Retry-After header gives the wait in seconds or as a date.

What the client should do next. Fix the request, or stop. Retrying a 400, 404, 409 or 422 unchanged gets the same answer every time, and a client that retries them in a loop turns one bad request into hundreds.

So the code should name the fix: read it as "the format", "the address", "the current state", "the values" or "the pace".