Article

Designing Good APIs

Design clear HTTP contracts, predictable errors, and safe retries with a library API example.

6 min read2026-12-02beginnerBy m7mdbook
On this page

Designing Good APIs

A good API contract tells clients how to send a request, interpret the response, and recover from a failure. Consider a library API where an editor creates an article and a reader fetches it.

Model resources and choose HTTP methods

Use POST /v1/articles to create an article when the server assigns its identifier. Return 201 Created with a Location header pointing to the new resource, such as /v1/articles/a42. A reader can then use GET /v1/articles/a42 to retrieve it.

Use GET for retrieval without asking the server to change the resource. PUT is suitable when the client intends to replace the state of the target resource with the submitted representation. Repeating the same PUT has the same intended effect as sending it once, even if the response changes.

Return predictable errors

Validate request fields at the boundary. For this example, a JSON body that parses but omits the required title returns 422 Unprocessable Content. A malformed JSON body can return 400 Bad Request. Document the distinction so clients know when to correct the payload.

Send errors as application/problem+json with a stable problem type and a readable explanation. This response uses errors as an extension defined by this particular API.

json
{
  "type": "https://example.com/problems/invalid-article",
  "title": "Article validation failed",
  "status": 422,
  "errors": [{ "field": "title", "code": "required" }]
}

Clients can handle the problem using type and attach a message to the relevant field using code. Keep those values stable as user-facing wording changes.

Define what clients can retry

A request can time out after the server has already written the article. Retrying an ordinary POST may create a duplicate. If the API promises safe retries for creation, document how the client sends a key identifying the operation and how the server handles repeated keys, conflicting payloads, and key expiration.

Evolve the contract deliberately

An optional field is usually a compatible addition for clients that accept unknown fields. Removing a field, changing its type, or making an optional request field mandatory can break existing clients. Keep the old contract available during a documented migration to a new version.

Test the contract

Exercise creation, retrieval, validation failure, and missing resources. If you promise retry protection, simulate a timeout after a successful write and verify that retrying creates only one article. Check both the HTTP status and the response fields that clients depend on.

Sources