HTTP methods, status codes and headers
HTTP is the language of web APIs. Using its methods, status codes and headers the way they were designed makes your API predictable: clients, browsers, caches and tools all understand it without reading your docs.
Methods
| Method | Meaning | Body? | Safe | Idempotent |
|---|---|---|---|---|
GET |
Read a resource | No | ✔ | ✔ |
POST |
Create a resource, or run an action | Yes | ||
PUT |
Replace a resource completely | Yes | ✔ | |
PATCH |
Change part of a resource | Yes | ||
DELETE |
Remove a resource | Usually no | ✔ | |
HEAD |
Like GET, but headers only | No | ✔ | ✔ |
OPTIONS |
Which methods are allowed (used by CORS) | No | ✔ | ✔ |
- Safe methods never change anything on the server. Browsers, crawlers and caches may send GET requests freely, so never change data in a GET handler (
GET /delete-accountis a classic bug). - Idempotent means repeating the request has the same effect as sending it once. Deleting order 7 twice leaves it deleted; setting a price with PUT twice leaves the same price. POST is not idempotent: sending "create order" twice creates two orders. That's why retries need care (see the rate limiting and idempotency lesson).
PUT vs PATCH
The PUT removed city because the client didn't send it. Most APIs offer PATCH for edits and use PUT rarely, or only where "replace" is really meant.
Status codes
The first digit tells you the category:
| Range | Category |
|---|---|
| 1xx | Informational (rare in APIs) |
| 2xx | Success |
| 3xx | Redirection: look elsewhere |
| 4xx | Client error: the request was wrong; don't retry unchanged |
| 5xx | Server error: the server failed; retrying later may work |
The ones you'll use constantly:
| Code | Name | Typical use |
|---|---|---|
| 200 | OK | Successful GET, PATCH, PUT |
| 201 | Created | Successful POST that created something (add a Location header) |
| 204 | No Content | Successful DELETE; nothing to return |
| 301 / 308 | Moved Permanently | A URL changed forever |
| 304 | Not Modified | The client's cached copy is still valid |
| 400 | Bad Request | Malformed JSON, invalid parameters |
| 401 | Unauthorized | Not authenticated (missing or bad credentials) |
| 403 | Forbidden | Authenticated, but not allowed |
| 404 | Not Found | No such resource |
| 405 | Method Not Allowed | DELETE /products when that isn't supported |
| 409 | Conflict | Duplicate email, editing a stale version |
| 415 | Unsupported Media Type | Sent XML to a JSON-only API |
| 422 | Unprocessable Content | Valid JSON, but fails business validation |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | An unexpected bug |
| 502 / 503 / 504 | Bad Gateway / Service Unavailable / Gateway Timeout | Upstream or overload problems |
Headers
Headers carry metadata as Name: value pairs. Names are case-insensitive.
| Header | Direction | Purpose |
|---|---|---|
Content-Type |
both | Format of the body: application/json, text/html, multipart/form-data |
Accept |
request | Formats the client can handle |
Authorization |
request | Credentials: Bearer <token>, Basic … |
User-Agent |
request | Which client is calling |
Location |
response | URL of a created resource or redirect target |
Cache-Control |
response | Whether and how long a response may be cached |
ETag |
response | A version fingerprint for caching (see the caching lesson) |
Set-Cookie / Cookie |
both | Cookies |
Retry-After |
response | When to try again (with 429 or 503) |
X-Request-Id |
both | Correlates logs for one request (custom) |
Content negotiation
The client says what it wants with Accept; the server picks the best format it supports:
HTTPS
Always serve APIs over HTTPS (HTTP over TLS). It encrypts requests and responses, so tokens, passwords and personal data can't be read or changed on the way, and it proves the server is who it claims to be. Certificates are free from Let's Encrypt, and cloud load balancers handle them for you.
Practice
- Add
DELETE /signups/:emailthat returns 204, or 404 if the email isn't registered. - Make
GET /signupsreturn the list of emails, and answer every other method with 405 and anAllowheader. - Add an
X-Request-Idheader to every response usingcrypto.randomUUID().
1.Which method should "mark order 7 as shipped" use?
2.A client sends valid JSON, but the email field already belongs to another account. Which status fits best?
3.What does "idempotent" mean?