Guide
HTTP for API testing: status codes, headers, CORS, caching
Most API bugs are not in the business logic. They are a wrong status code, a missing header, a CORS rule or a cached response. This guide covers the parts of HTTP that come up every time you test or debug an API, with curl commands you can run against any endpoint.
Reading a request and a response
curl -i shows the response headers; -v also shows the request curl sent, which is the first thing to check when an API says your request is wrong:
curl -v https://api.example.com/users/42 \
-H "Accept: application/json" \
-H "Authorization: Bearer $TOKEN"> GET /users/42 HTTP/2
> Host: api.example.com
> Accept: application/json
> Authorization: Bearer eyJ...
>
< HTTP/2 200
< content-type: application/json; charset=utf-8
< cache-control: private, max-age=0
< etag: "a1b2c3"
<
{"id":42,"name":"Asha"}Lines starting with > were sent, < received. A request is a method, a path, headers and an optional body; a response is a status code, headers and an optional body. Everything below is about getting those right.
Methods and idempotency
| Method | Purpose | Safe | Idempotent |
|---|---|---|---|
| GET | Read a resource | Yes | Yes |
| HEAD | Like GET, headers only | Yes | Yes |
| POST | Create, or run an action | No | No |
| PUT | Replace a resource entirely | No | Yes |
| PATCH | Change part of a resource | No | Not guaranteed |
| DELETE | Remove a resource | No | Yes |
| OPTIONS | Ask what is allowed (CORS preflight) | Yes | Yes |
Idempotent means sending the same request twice has the same effect as sending it once. That matters for retries: a client can safely retry a timed-out PUT or DELETE, but retrying a POST may create two orders. APIs that must accept retried POSTs (payments, job submissions) use an idempotency key, a unique header the client sends so the server can recognise a repeat.
curl -X POST https://api.example.com/payments \
-H "Idempotency-Key: 6f1c2b9e-4d7a-4b1e-9c3f-0a8d5e2f7b61" \
--json '{"amount": 4900, "currency": "INR"}'--json (curl 7.82 and later) sets Content-Type and Accept to application/json and sends the body; on older curl use -H "Content-Type: application/json" -d '…'.
Status codes that matter
| Code | Meaning | Typical cause |
|---|---|---|
| 200 OK | Success with a body | |
| 201 Created | A resource was created | POST; the Location header points at it |
| 204 No Content | Success, deliberately no body | DELETE, or a PUT that returns nothing |
| 301 / 308 | Moved permanently | 308 keeps the method and body; 301 may turn POST into GET |
| 302 / 307 | Moved temporarily | 307 keeps the method and body; 302 may turn POST into GET |
| 304 Not Modified | Your cached copy is still valid | Conditional GET with If-None-Match |
| 400 Bad Request | The request is malformed | Invalid JSON, wrong types |
| 401 Unauthorized | Not authenticated | Missing or expired credentials |
| 403 Forbidden | Authenticated, but not allowed | Wrong role or scope |
| 404 Not Found | No such resource | Wrong path or id, or hidden from you |
| 405 Method Not Allowed | Wrong method for this path | POST to a read-only endpoint |
| 409 Conflict | Clashes with current state | Duplicate, or a version conflict |
| 415 Unsupported Media Type | Body format not accepted | Missing or wrong Content-Type |
| 422 Unprocessable Content | Well-formed, but invalid | Validation errors |
| 429 Too Many Requests | Rate limited | Back off; read Retry-After |
| 500 Internal Server Error | The server failed | A bug; not your request's fault |
| 502 / 504 | Gateway error or timeout | The upstream service is down or slow |
| 503 Service Unavailable | Temporarily unavailable | Maintenance or overload |
Two distinctions catch people out. 401 means "I do not know who you are" (log in again); 403 means "I know who you are, and you may not" (logging in again will not help). And a 4xx is the client's problem to fix while a 5xx is the server's, which is why only 5xx and 429 responses are generally worth retrying.
Headers worth knowing
Content-Typedescribes the body you send or receive (application/json,multipart/form-data). A JSON body sent without it is a common cause of 400 and 415 errors.Acceptsays what you want back. Some APIs return HTML error pages unless you ask for JSON.Authorizationcarries credentials, usuallyBearer <token>orBasic <base64 of user:password>. Basic is encoding, not encryption; use it only over HTTPS.Location(with 201 and 3xx) points at the created resource or the redirect target.Retry-After(with 429 and 503) says how long to wait, in seconds or as a date.ETagandLast-Modifiedidentify a version of the response for caching and for safe concurrent updates withIf-Match.
CORS: why it works in curl and fails in the browser
Cross-Origin Resource Sharing is enforced by browsers, not by servers or by curl. When JavaScript on https://app.example calls https://api.example, a different origin, the browser sends the request and then refuses to let the page read the response unless the API's response allows that origin. curl and server-side code never apply this rule, so the same request "works" there.
For requests other than simple ones, the browser first sends a preflight OPTIONS request asking permission. A request needs a preflight if it uses a method other than GET, HEAD or POST, a custom header such as Authorization, or a Content-Type other than form encoding, multipart or plain text, so any JSON POST does.
OPTIONS /orders HTTP/1.1
Origin: https://app.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization, content-type
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: authorization, content-type
Access-Control-Max-Age: 600- The preflight must return a 2xx status with the allow headers. A 401 or 404 on
OPTIONS(often because authentication middleware runs before CORS) fails it. - The actual response also needs
Access-Control-Allow-Origin, not just the preflight. - With cookies or credentials (
fetch(url, {credentials: "include"})), the origin must be named exactly;*is not allowed, andAccess-Control-Allow-Credentials: trueis required. - To let the page read custom response headers, list them in
Access-Control-Expose-Headers.
You can reproduce a preflight with curl to see what the server answers:
curl -i -X OPTIONS https://api.example.com/orders \
-H "Origin: https://app.example" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: authorization, content-type"CORS protects users, not APIs: it stops a malicious page from reading responses with a visitor's cookies. It is not access control. Anyone can still call your API from curl, so authentication and authorisation remain the server's job.
Caching and conditional requests
Cache-Control: no-storemeans never store the response; use it for personal data.Cache-Control: no-cachemeans store it, but revalidate with the server before every use. It does not mean "do not cache".Cache-Control: max-age=3600lets clients and shared caches reuse it for an hour; addprivateto keep it out of shared caches.ETagplusIf-None-Matchturns a repeat GET into a tiny 304 when nothing changed.
# First request returns the ETag; the second sends it back
curl -i https://api.example.com/catalog
curl -i https://api.example.com/catalog -H 'If-None-Match: "a1b2c3"'
# HTTP/2 304 (no body: your copy is current)When a fix "does not show up", suspect a cache before suspecting the fix: a CDN, a service worker or the browser may be serving an older response. The Age header and the CDN's own cache-status header tell you where it came from.
A testing checklist
- Happy path: correct status (200, 201 or 204), correct body shape, correct
Content-Type. - Authentication: no token gives 401, a valid token without permission gives 403, an expired token gives 401.
- Validation: malformed JSON gives 400, invalid values give 400 or 422 with field-level messages.
- Not found: unknown ids give 404, and someone else's ids do not leak that they exist.
- Idempotency: repeat PUT and DELETE safely; repeat a POST with the same idempotency key and get the original result.
- Limits: hammer an endpoint and expect 429 with
Retry-After. - Browser clients: a preflight from the real origin succeeds, and from an unknown origin does not.
For quick manual checks, the Online Code Editor includes an HTTP client next to your code. Its requests are sent from our server rather than from your browser, so CORS does not get in the way, and requests to private addresses such as localhost are blocked for safety; test local services with curl instead.