API Design
RESTful APIs
Resources, Verbs, Status Codes, and Versioning strategies.
REST (Representational State Transfer)
REST is the default language of the web. It treats everything as a Resource (noun) that can be manipulated via standard HTTP Verbs (verbs).
The Verbs
Don't just use POST for everything. Semantics matter for caching and idempotency.
| Verb | Action | Idempotent? | Safe? |
|---|---|---|---|
| GET | Read a resource. | Yes | Yes |
| POST | Create a new resource. | No | No |
| PUT | Replace a resource entirely (Update). | Yes | No |
| PATCH | Partial update (Modify specific fields). | No* | No |
| DELETE | Remove a resource. | Yes | No |
Note: PATCH can be idempotent, but isn't guaranteed by spec.
Status Codes
Your API is a UI for developers. Give them helpful error codes.
- 2xx (Success):
200 OK: Standard success.201 Created: Result of a POST.202 Accepted: Async job started (don't wait for result).
- 4xx (Client Error):
400 Bad Request: Validation failed.401 Unauthorized: Who are you? (Auth token missing).403 Forbidden: I know who you are, but you can't touch this.429 Too Many Requests: Slow down.
- 5xx (Server Error):
500: We broke something.502/504: The upstream service timed out (Gateway errors).
Versioning Strategies
APIs evolve. You will eventually need to break backward compatibility.
1. URI Versioning (The Standard)
GET /api/v1/users
- Pros: Explicit, easy to cache, easy to browse.
- Cons: "Pollutes" the URI space.
2. Header Versioning
Accept: application/vnd.myapi.v1+json
- Pros: Keeps URIs clean (
/users). Pure "REST". - Cons: Harder to test in browser/curl. Cache fragmentation.
Richardson Maturity Model
A heuristic for how "RESTful" an API is.
- Level 0: The Swamp of POX. Using HTTP as a tunnel for RPC (e.g., one endpoint
/apithat accepts big XML blobs). - Level 1: Resources. Using
/usersand/orders. - Level 2: HTTP Verbs. Using
GET/POST/DELETEcorrectly. (Most modern APIs stop here). - Level 3: HATEOAS (Hypermedia). The API returns links to other actions.
- Reality Check: HATEOAS sounds great in theory but is tedious to implement and rarely used by frontend clients in practice.