Konubinix' opinionated web of thoughts

Design Better APIs

Fleeting

How to design better APIs

The best APIs I know are predictable. When a consumer uses and understands one endpoint, they can expect that another endpoint works the same way

https://r.bluethl.net/how-to-design-better-apis

Every endpoint should require authorization by default.

https://r.bluethl.net/how-to-design-better-apis

Provide an endpoint (for example GET /health) that determines whether or not a service is healthy

https://r.bluethl.net/how-to-design-better-apis

Even the first version of the API (1.0) should be explicitly versioned

https://r.bluethl.net/how-to-design-better-apis

Some examples:

https://api.averagecompany.com/v1/health

https://api.averagecompany.com/health?api_version=1.0

https://r.bluethl.net/how-to-design-better-apis

If an API needs to be called by a third party, it makes sense to allow authentication via API keys

https://r.bluethl.net/how-to-design-better-apis

Use conventional HTTP status codes to indicate the success or failure of a request. Don’t use too many, and use the same status codes for the same outcomes across the API.

https://r.bluethl.net/how-to-design-better-apis

Some examples:

200 for general success 201 for successful creation 400 for bad requests from the client 401 for unauthorized requests 403 for missing permissions 404 for missing resources 429 for too many requests 5xx for internal errors (these should be avoided at all costs)

https://r.bluethl.net/how-to-design-better-apis

There are many HTTP methods, but the most important ones are:

POST for creating resources POST /users

GET for reading resources (both single resources and collections) GET /users GET /users/{id}

PATCH for applying partial updates to a resource PATCH /users/{id}

PUT for applying full updates to a resource (replaces the current resource) PUT /users/{id}

DELETE for deleting resources DELETE /users/{id}

https://r.bluethl.net/how-to-design-better-apis

Most endpoints are resource-oriented and should be named that way.

https://r.bluethl.net/how-to-design-better-apis

always use a standardized error response that includes more detailed information on what went wrong

https://r.bluethl.net/how-to-design-better-apis

good idea to return the created resource after creating it with a POST request.

https://r.bluethl.net/how-to-design-better-apis

usually a good idea to design updates around PATCH requests

https://r.bluethl.net/how-to-design-better-apis

good idea to be as specific as possible when designing endpoints

https://r.bluethl.net/how-to-design-better-apis

Paginate all requests that return a collection of resources and use the same response structure. Use page_number and page_size (or similar) to control which chunk you want to retrieve.

https://r.bluethl.net/how-to-design-better-apis

Allow consumers to load related data using a query parameter called expand (or similar).

https://r.bluethl.net/how-to-design-better-apis