Designing APIs
An API is the set of requests other programs can send to your app. A good API is easy to guess and hard to misuse.
Resources and methods
In a REST API, the URL names a thing, using nouns: /users/42, /orders/7. The HTTP method says what to do with it:
- GET /orders/7 reads order 7.
- POST /orders creates a new order.
- PUT /orders/7 replaces order 7; PATCH changes part of it.
- DELETE /orders/7 removes it.
Avoid verbs in the URL, like /getOrder or /deleteOrder. A GET must never change data.
Status codes
- 201 Created: a POST made something new. 200 OK is plain success.
- 400 Bad Request: the input is wrong.
- 401 Unauthorized: we don't know who you are.
- 403 Forbidden: we know who you are, but you may not do this.
- 404 Not Found and 429 Too Many Requests.
- 500 Internal Server Error: the server broke.
4xx means the client must change something. 5xx means the server failed.
Pagination
Never return a million items at once. Return pages, like 20 items at a time.
Offset paging asks to skip 40 items and take 20. If a new item is added at the top, everything shifts, and the next page repeats an item. The database also steps past every skipped row, so deep pages get slow.
Cursor paging asks for 20 items after item X. It goes on exactly where you stopped, and stays fast. But you can't jump straight to page 50.
Versioning
Old app versions stay on phones for months. Adding a new field is usually safe. Removing or renaming a field breaks them. For a change like that, add /v2/ and keep /v1/ running until old clients move.
Focused responses
Return the fields the client needs, not the whole database row. Never send private data like password hashes. Smaller responses are faster, mainly on phones.
Remember
- Nouns in the URL, verbs in the method.
- 4xx is the client's fault, 5xx is the server's.
- Cursors stay correct when new items arrive.
- Never break /v1/; add /v2/.
- Send only what the client needs.