Design Better APIs
Fleeting- External reference: https://r.bluethl.net/how-to-design-better-apis
How to design better APIs
- see,
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
Every endpoint should require authorization by default.
Provide an endpoint (for example GET /health) that determines whether or not a service is healthy
Even the first version of the API (1.0) should be explicitly versioned
Some examples:
https://api.averagecompany.com/v1/health
If an API needs to be called by a third party, it makes sense to allow authentication via API keys
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.
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)
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}
Most endpoints are resource-oriented and should be named that way.
always use a standardized error response that includes more detailed information on what went wrong
good idea to return the created resource after creating it with a POST request.
usually a good idea to design updates around PATCH requests
good idea to be as specific as possible when designing endpoints
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.
Allow consumers to load related data using a query parameter called expand (or similar).