Card 01/ 08

ConceptDifficulty: Beginner2 min

An Error Is Part of the Contract

A client branches on errors as often as on success, so the error format deserves the same design.

An error response is as much part of the API contract as a success, and it needs one shape across the whole API. A client needs three things from it: the status code, to know the class of failure; a stable code, to branch on in its program; and enough detail, for a person to fix the request. An API whose endpoints fail in different shapes makes every client write a parser per endpoint.

Three endpoints with their own error shapes, and the same three with one shape

Three shapesone per endpoint

/orders answers {"error": "bad quantity"}. /users answers {"message": "Invalid", "code": 12}. /payments answers the plain text Payment failed. A client needs three parsers and still cannot tell which failures are the same kind.

One shapefor the whole API

Every endpoint answers with the same fields: a type naming the kind of error, a title and detail for people, the status, and an errors list for invalid fields. One parser handles every failure.

The status code still comes first. The body explains the failure, but the code decides how software treats it. A 422 with a well-designed body is right; a 200 with the same body is still wrong, because caches and monitoring read the code.

What a client does with an error. A program branches: show a form field in red, refresh a token, wait and retry, or give up. A person reads: the developer integrating the API, or a user shown the message. The format must serve both, with a code for the program and text for the person.

Write errors into the contract. For each operation, list the status codes it may return and the error types each can carry, as the success response is listed. A client that knows POST /orders can fail with out-of-stock can handle it; one that finds out in production cannot.

So design the error shape once, before the first endpoint, and make every endpoint use it.

← → move through sections and cards