# HTTP API cheatsheet

Source: https://codewiki.com/cheatsheets/http/

## Resources and methods

- `GET /orders/ord-42` — retrieve a representation without changing resource state; safe and idempotent
- `HEAD /orders/ord-42` — retrieve response metadata without response content; safe and idempotent
- `POST /orders` — ask a collection to process a representation; commonly creates a member and is not inherently idempotent
- `PUT /orders/ord-42` — create or replace the representation at a known target; idempotent
- `PATCH /orders/ord-42` — apply a partial modification defined by the patch media type; not inherently idempotent
- `DELETE /orders/ord-42` — request removal of the target; the intended effect is idempotent
- `OPTIONS /orders` — request communication options for the target; safe and idempotent

## Node client

- `const response = await fetch('https://api.example.com/orders')` — send a GET request with the Node 24 global `fetch`
- `await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(order) })` — send JSON with an explicit request media type
- `response.ok` — test whether the status is in the 200–299 range
- `response.headers.get('content-type')` — read a response header case-insensitively
- `const data = await response.json()` — consume the response content once and parse it as JSON
- `await fetch(url, { signal: AbortSignal.timeout(5000) })` — abort the request after five seconds

## Success responses

- `200 OK` — return a successful representation or operation result
- `201 Created` — report that the request created a resource
- `Location: /orders/ord-42` — identify the created resource in a `201` response
- `202 Accepted` — report accepted but unfinished processing; define how clients observe completion
- `204 No Content` — report success with no response content

## Client failures

- `400 Bad Request` — reject malformed syntax, framing, or request input
- `401 Unauthorized` — reject missing or invalid authentication and send a challenge
- `403 Forbidden` — refuse an understood request that the caller is not allowed to perform
- `404 Not Found` — report an absent resource, or conceal one the caller must not discover
- `409 Conflict` — report a conflict with the resource's current state
- `412 Precondition Failed` — reject a request whose conditional header evaluated false
- `422 Unprocessable Content` — reject well-formed content whose instructions cannot be processed

## Server pressure

- `429 Too Many Requests` — report that this client exceeded a rate limit
- `500 Internal Server Error` — report an unexpected server failure without exposing internals
- `502 Bad Gateway` — report that a gateway received an invalid upstream response
- `503 Service Unavailable` — report temporary overload or maintenance
- `504 Gateway Timeout` — report that a gateway did not receive an upstream response in time
- `Retry-After: 120` — tell the client to wait 120 seconds after `429` or `503`

## Representations

- `Content-Type: application/json` — identify the media type of request or response content
- `Accept: application/json` — request a JSON response representation
- `Content-Type: application/problem+json` — identify an RFC 9457 problem-details document
- `406 Not Acceptable` — report that no available response representation meets `Accept`
- `415 Unsupported Media Type` — reject request content in an unsupported format or encoding
- `Content-Encoding: gzip` — declare that the representation data uses gzip content coding

## Caching

- `Cache-Control: no-store` — tell caches not to store this response
- `Cache-Control: private, max-age=60` — allow a private cache to reuse the response while it is fresh
- `Cache-Control: public, max-age=300` — allow shared caches to reuse the response when the contract permits it
- `ETag: "order-7"` — attach an opaque validator to the selected representation
- `If-None-Match: "order-7"` — revalidate a cached representation with its entity tag
- `304 Not Modified` — reuse the cached representation; the response carries no message content
- `Vary: Accept-Encoding` — keep separate cache entries for requests with different accepted encodings

## Concurrency and retries

- `If-Match: "order-7"` — apply a mutation only while the current strong entity tag matches
- `428 Precondition Required` — require the client to make the request conditional
- `idempotent: GET, HEAD, OPTIONS, PUT, DELETE` — repeating an identical request has the same intended effect as one request
- `not inherently idempotent: POST, PATCH` — retry only when the application contract supplies safe deduplication semantics
- `Idempotency-Key: 7b1d7a90` — reuse one application-defined key and payload for every retry of the same logical operation

## Pagination

- `GET /orders?status=pending` — filter a collection with a documented query parameter
- `GET /orders?limit=50` — request a bounded page size; the server still enforces a maximum
- `GET /orders?cursor=eyJpZCI6Im9yZC00MiJ9` — continue from an opaque cursor bound to the same filters and ordering
- `ORDER BY created_at DESC, id DESC` — use a unique tie-breaker to make the page order total and deterministic
- `Link: </orders?cursor=next>; rel="next"` — advertise the next page target without asking the client to construct it

## Auth and CORS

- `Authorization: Bearer ACCESS_TOKEN` — send a bearer access token over TLS to the resource server
- `WWW-Authenticate: Bearer realm="orders"` — challenge a request with missing or invalid bearer credentials
- `Origin: https://app.example.com` — identify the initiating browser origin; this is not user authentication
- `Access-Control-Allow-Origin: https://app.example.com` — allow that origin to expose the cross-origin response to browser code
- `Access-Control-Allow-Methods: GET, POST` — list methods allowed by the preflight response
- `Access-Control-Allow-Headers: Authorization, Content-Type` — list non-safelisted request headers allowed by preflight
- `Access-Control-Allow-Credentials: true` — permit credentialed browser requests only with an explicit allowed origin

## Evolution

- `GET /api/v1/orders` — select a major API contract in the path
- `Accept: application/vnd.example.orders.v2+json` — select a versioned representation through content negotiation
- `Vary: Accept` — prevent a cache from mixing representations selected by `Accept`
- `Deprecation: @1798761600` — signal a deprecation instant as an RFC 9651 date without changing current behavior
- `Sunset: Thu, 01 Jul 2027 00:00:00 GMT` — signal when the resource is expected to become unresponsive

## Contract checks

- `import assert from 'node:assert/strict'` — use strict Node assertions in an API contract test
- `assert.equal(response.status, 201)` — pin the operation's exact success status
- `assert.equal(response.headers.get('location'), '/orders/ord-42')` — pin a required response header
- `assert.deepEqual(await response.json(), expectedBody)` — pin the promised response representation
- `assert.equal(await response.text(), '')` — verify that a `204` response has no content
- `assert.equal(response.headers.get('etag'), expectedEtag)` — pin the validator needed by conditional requests
