Skip to content

Guide

HTTP for API testing: status codes, headers, CORS, caching

By Vishnu KumarPublished 7 min read

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

HTTP methods used by APIs
MethodPurposeSafeIdempotent
GETRead a resourceYesYes
HEADLike GET, headers onlyYesYes
POSTCreate, or run an actionNoNo
PUTReplace a resource entirelyNoYes
PATCHChange part of a resourceNoNot guaranteed
DELETERemove a resourceNoYes
OPTIONSAsk what is allowed (CORS preflight)YesYes

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

Status codes you will meet while testing APIs
CodeMeaningTypical cause
200 OKSuccess with a body
201 CreatedA resource was createdPOST; the Location header points at it
204 No ContentSuccess, deliberately no bodyDELETE, or a PUT that returns nothing
301 / 308Moved permanently308 keeps the method and body; 301 may turn POST into GET
302 / 307Moved temporarily307 keeps the method and body; 302 may turn POST into GET
304 Not ModifiedYour cached copy is still validConditional GET with If-None-Match
400 Bad RequestThe request is malformedInvalid JSON, wrong types
401 UnauthorizedNot authenticatedMissing or expired credentials
403 ForbiddenAuthenticated, but not allowedWrong role or scope
404 Not FoundNo such resourceWrong path or id, or hidden from you
405 Method Not AllowedWrong method for this pathPOST to a read-only endpoint
409 ConflictClashes with current stateDuplicate, or a version conflict
415 Unsupported Media TypeBody format not acceptedMissing or wrong Content-Type
422 Unprocessable ContentWell-formed, but invalidValidation errors
429 Too Many RequestsRate limitedBack off; read Retry-After
500 Internal Server ErrorThe server failedA bug; not your request's fault
502 / 504Gateway error or timeoutThe upstream service is down or slow
503 Service UnavailableTemporarily unavailableMaintenance 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-Type describes 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.
  • Accept says what you want back. Some APIs return HTML error pages unless you ask for JSON.
  • Authorization carries credentials, usually Bearer <token> or Basic <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.
  • ETag and Last-Modified identify a version of the response for caching and for safe concurrent updates with If-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
  1. 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.
  2. The actual response also needs Access-Control-Allow-Origin, not just the preflight.
  3. With cookies or credentials (fetch(url, {credentials: "include"})), the origin must be named exactly; * is not allowed, and Access-Control-Allow-Credentials: true is required.
  4. 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-store means never store the response; use it for personal data.
  • Cache-Control: no-cache means store it, but revalidate with the server before every use. It does not mean "do not cache".
  • Cache-Control: max-age=3600 lets clients and shared caches reuse it for an hour; add private to keep it out of shared caches.
  • ETag plus If-None-Match turns 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.