HTTP Cheatsheet

A thorough, student-friendly guide to HTTP: requests, responses, methods, headers, caching, cookies, security headers, HTTP versions, and a complete list of status codes with clear explanations.

What is HTTP?

HTTP (HyperText Transfer Protocol) is the protocol used by web browsers and servers to communicate. It defines how requests are sent, how responses look, and the rules for resources on the web.

Think of HTTP as a language both browser and server speak: browser asks (requests), server answers (responses).

HTTP Request Structure

A request contains a method, URL (path), HTTP version, headers, and an optional body.

GET /path/resource?id=10 HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Accept: application/json
Accept-Language: en-US

<optional body for POST/PUT>
  • Method: what you want to do (GET, POST, etc.).
  • URL / Path: resource you want from the server.
  • Headers: metadata (content type, auth tokens, caching hints).
  • Body: data sent with some methods (POST, PUT, PATCH).

HTTP Response Structure

A response has a status line (status code + reason), headers, and a body (often HTML, JSON, images, etc.).

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 45
Cache-Control: max-age=3600

{ "id": 10, "name": "Alice", "active": true }

The status code helps the client know what happened (success, redirect, client error, server error).

HTTP Methods (Verbs)

Methods indicate the desired action. Here are the most common ones and how to think about them.

GET

Retrieve a representation of a resource. Should be safe (no side effects) and idempotent (multiple identical requests have same effect).

GET /posts/1

POST

Create a new resource or perform a processing action. Not idempotent by default (multiple POSTs may create multiple resources).

POST /posts
Content-Type: application/json

{ "title": "New Post", "body": "Hello" }

PUT

Replace an entire resource at the given URL. Typically idempotent: repeating the same PUT won't change result beyond first application.

PUT /posts/1
Content-Type: application/json

{ "title": "Updated", "body": "New body" }

PATCH

Partially update a resource. Often used when you only want to change a few fields.

PATCH /posts/1
Content-Type: application/json

{ "title": "Small edit" }

DELETE

Remove a resource. Usually idempotent: deleting an already-removed resource typically returns 404 or 204 depending on design.

DELETE /posts/1

HEAD

Same as GET but server returns only headers (no body). Useful for checking metadata or caching without downloading content.

OPTIONS

Ask the server which methods and headers are supported for a resource. Common with CORS preflight checks.

Common HTTP Headers

Headers transmit metadata. There are request headers, response headers, and entity headers.

Important Request Headers

  • Host: which host the client wants (domain + optional port).
  • User-Agent: identifies the client (browser or app).
  • Accept: which response content types are acceptable (e.g. application/json).
  • Accept-Language: preferred languages.
  • Authorization: credentials (e.g. Bearer <token>).
  • Content-Type: type of request body (e.g. application/json).
  • Content-Length: size of the request body in bytes.
  • If-Modified-Since/If-None-Match: conditional requests for caching.

Important Response Headers

  • Content-Type: type of response body (e.g. text/html, application/json).
  • Content-Length: response body size.
  • Cache-Control: caching rules for clients and proxies.
  • ETag: an identifier for a version of the resource used by caches.
  • Set-Cookie: ask the client to store cookies.
  • Location: new URL for redirections (301/302/201).
  • WWW-Authenticate: used with 401 Unauthorized to indicate needed auth scheme.

Example: JSON POST request

POST /api/items HTTP/1.1
Host: example.com
Content-Type: application/json
Authorization: Bearer abc123

{ "name": "Widget", "qty": 10 }

Cookies & Sessions

Cookies are small pieces of data set by servers in the browser. They are used to keep session state (e.g. logged-in user). They are sent automatically on subsequent requests to the same domain.

Setting a cookie:

Set-Cookie: sessionId=abc123; Path=/; HttpOnly; Secure; SameSite=Lax
  • HttpOnly: cookie inaccessible to JavaScript (protects from XSS).
  • Secure: only send cookie over HTTPS.
  • SameSite: limits cross-site sending (Lax, Strict, None).
  • Cookies have size limits and are sent with every request, so avoid storing large data in them.

Caching

Caching improves performance by storing copies of resources. HTTP provides directives to control caching behavior for browsers and proxies.

Cache-Control

Most important header for caching. Example values:

Cache-Control: max-age=3600, public
Cache-Control: no-cache
Cache-Control: no-store
  • max-age: seconds cached.
  • public / private: whether proxies can cache.
  • no-cache: must revalidate with server before using cached copy.
  • no-store: do not store at all.

ETag & Conditional Requests

ETag is a fingerprint for a resource. Clients can ask the server if content changed using If-None-Match. If not changed, server returns 304 Not Modified (no body), saving bandwidth.

ETag: "abc123"
If-None-Match: "abc123"
--> 304 Not Modified

Security Headers

Use these headers to harden your web app against common attacks.

Content-Security-Policy (CSP)

Controls which sources are allowed to load scripts, styles, images, etc. Helps reduce XSS attacks.

Content-Security-Policy: default-src 'self'; img-src 'self' https://images.example.com;

Strict-Transport-Security (HSTS)

Force browsers to use HTTPS. Set long durations in production.

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

X-Content-Type-Options

Prevents MIME-type sniffing.

X-Content-Type-Options: nosniff

Referrer-Policy

Controls how much referrer information is sent with requests.

Referrer-Policy: no-referrer-when-downgrade

X-Frame-Options

Protects against clickjacking by controlling if the page can be framed.

X-Frame-Options: DENY

HTTP Versions (1.1, 2, 3)

HTTP evolved to improve speed and reliability:

  • HTTP/1.1 — persistent connections (keep-alive), chunked responses, widely supported.
  • HTTP/2 — multiplexing (multiple requests/responses on single connection), header compression, server push. Improves latency.
  • HTTP/3 — runs over QUIC (UDP-based), reduces connection/setup latency and improves reliability on lossy networks.

HTTP Status Codes (Grouped)

Status codes are grouped by class. Each code tells the client what happened.

1xx — Informational

Temporary responses to indicate progress.

100 Continue — The client may continue with the request (often used when client sends large body after initial check). Server indicates everything is OK so far.
101 Switching Protocols — Server is switching protocols as requested by client (e.g., HTTP -< WebSocket).
102 Processing (WebDAV) — Server received request and is processing, but no response yet.
103 Early Hints — Sent before final response to allow user agent to start preloading resources (improves performance).

2xx — Success

The request was received, understood, and accepted.

200 OK — Standard success response. The body contains the requested resource or result.
201 Created — A new resource was created. Response should include a Location header pointing to the new resource.
202 Accepted — Request accepted for processing but not completed (useful for async operations).
203 Non-Authoritative Information — Response from a third-party copy; metadata may differ from origin server.
204 No Content — Success but no body returned (useful for DELETE or when response body is unnecessary). Client should not change current document view.
205 Reset Content — Instructs client to reset form or view (rare).
206 Partial Content — Returned when serving a range of the resource (byte-range requests), used for resumable downloads.
207 Multi-Status (WebDAV) — Multiple status codes for different parts of a multi-operation request.
208 Already Reported (WebDAV) — Member of a collection has already been enumerated in a previous response.
226 IM Used — The server completed a request for the resource and the response is a representation of the result of one or more instance-manipulations (RFC 3229).

3xx — Redirection

Further action needed to fulfill the request (usually a redirect).

300 Multiple Choices — Multiple options for the resource; user-agent or user chooses.
301 Moved Permanently — Resource moved permanently to new URL. Clients and search engines should update links (SEO important).
302 Found (Temporary Redirect) — Resource temporarily at a different URL. Historically overloaded, many frameworks differentiate 302 vs 307.
303 See Other — Response stored at another URI and should be retrieved using GET (useful after POST to avoid resubmission).
304 Not Modified — Used with caching. Resource not changed since last request (client can use cached copy).
305 Use Proxy — Deprecated: suggests using a proxy, rarely used.
306 (Unused) — Previously used, now unused.
307 Temporary Redirect — Like 302 but method must not change (POST stays POST).
308 Permanent Redirect — Like 301 but method must not change (useful when redirecting POST to POST).

4xx — Client Errors

The request contains bad syntax or cannot be fulfilled by the server.

400 Bad Request — Server cannot process request due to client error (malformed syntax, invalid request).
401 Unauthorized — Authentication required (or invalid credentials). Use WWW-Authenticate header to indicate auth method.
402 Payment Required — Reserved for future use (payment). Rarely used in practice.
403 Forbidden — Server understood request but refuses to authorize it (client shouldn’t retry with different credentials).
404 Not Found — Resource not found. Common when URL is incorrect or resource removed.
405 Method Not Allowed — Method not allowed on the resource (e.g., POST where only GET is supported). Server should return Allow header listing allowed methods.
406 Not Acceptable — Server can’t produce a response matching the Accept headers.
407 Proxy Authentication Required — Client must authenticate with proxy.
408 Request Timeout — Client took too long to send the request.
409 Conflict — Request conflicts with current state of the server (e.g., edit conflict).
410 Gone — Resource permanently removed and no forwarding address known.
411 Length Required — Server requires Content-Length header.
412 Precondition Failed — Client provided preconditions (like If-Match) that are not met.
413 Payload Too Large — Request body is larger than server is willing to process.
414 URI Too Long — Request URI is too long for the server to process.
415 Unsupported Media Type — Server refuses to accept request because the payload format is unsupported (check Content-Type).
416 Range Not Satisfiable — Client asked for a portion of the file but the server cannot supply it (invalid range).
417 Expectation Failed — Server cannot meet the requirements of the Expect request header.
418 I'm a teapot — April Fools' joke from RFC 2324; not used in practice but sometimes returned for fun.
421 Misdirected Request — Request was directed to a server that cannot produce a response (HTTP/2 related).
422 Unprocessable Entity (WebDAV) — The request was well-formed but could not be processed due to semantic errors (e.g., validation failure).
423 Locked (WebDAV) — Resource is locked.
424 Failed Dependency (WebDAV) — Request failed due to failure of a previous request.
425 Too Early — Server is unwilling to process request that might be replayed (prevents certain replay attacks).
426 Upgrade Required — Client should switch to a different protocol (e.g., TLS/1.0 -< TLS/1.2).
428 Precondition Required — Server requires the request to be conditional (helps prevent lost updates).
429 Too Many Requests — Client sent too many requests in a given time (rate limiting). Use Retry-After header when appropriate.
431 Request Header Fields Too Large — Request headers too large for the server to process.
451 Unavailable For Legal Reasons — Resource unavailable due to legal reasons (e.g., censorship).

5xx — Server Errors

Server failed to fulfill a valid request. These are server-side issues.

500 Internal Server Error — Generic server error. Logs are needed to find the root cause.
501 Not Implemented — Server does not support requested functionality (e.g., method not implemented).
502 Bad Gateway — Server acting as gateway/proxy received invalid response from upstream server.
503 Service Unavailable — Server is overloaded or down for maintenance. Often temporary.
504 Gateway Timeout — Gateway/proxy timed out waiting for upstream server.
505 HTTP Version Not Supported — Server does not support the HTTP protocol version used in the request.
506 Variant Also Negotiates — Server configuration error during content negotiation.
507 Insufficient Storage (WebDAV) — Server cannot store the representation needed to complete the request.
508 Loop Detected (WebDAV) — Server detected an infinite loop while processing a request.
510 Not Extended — Further extensions to the request are required for the server to fulfill it.
511 Network Authentication Required — Client needs to authenticate to gain network access (e.g., captive portal).

Practical Examples & Tips

Using Fetch (browser)

fetch('/api/items', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Widget' })
})
  .then(r => {
    if (!r.ok) throw new Error('Request failed: ' + r.status);
    return r.json();
  })
  .then(data => console.log(data));

cURL Examples

# GET
curl -i https://api.example.com/posts/1

# POST JSON
curl -i -X POST https://api.example.com/posts \
  -H "Content-Type: application/json" \
  -d '{"title":"Hi","body":"Hello"}'

Handling 429 Rate Limits

Respect Retry-After header and implement exponential backoff.

Design tip: API Versioning

Include a version in the URL or in headers (e.g., /v1/users) so you can change the API without breaking clients.

How to use this page

  1. Read the request/response structure to understand the pieces of HTTP messages.
  2. Practice common methods (GET/POST/PUT/PATCH/DELETE) with cURL or fetch.
  3. Learn essential headers (Content-Type, Authorization, Cache-Control, ETag).
  4. Use the status codes list to understand server responses and design API behavior.

🚀 Explore More Free Developer Tools

Don’t stop here! Supercharge your workflow with our other powerful converters & formatters.

💡 New tools are added regularly — bookmark DevUtilsX and stay ahead!

Want to support my work?

Buy me a coffee