HTTP
The protocol of the web — requests and responses, methods, status codes, headers, caching, cookies, CORS, and the evolution from HTTP/1.1 to HTTP/2 and HTTP/3.
HTTP (Hypertext Transfer Protocol) is a request–response protocol: a client sends a request, a server returns a response. It began as a way to fetch HTML documents and is now the universal protocol for APIs, mobile apps, microservices and most of the Internet's traffic.
Anatomy of a request and response
GET /api/users/42?fields=name HTTP/1.1
Host: api.example.com
Accept: application/json
Authorization: Bearer eyJhbGciOi...
User-Agent: curl/8.4.0HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 27
Cache-Control: max-age=60
ETag: "a1b2c3"
{"id":42,"name":"Ada"}A request has a method, a path (with an optional query string), headers and an optional body. A response has a status code, headers and a body. HTTP/1.1 is plain text; HTTP/2 and HTTP/3 encode the same semantics in binary frames.
Methods
| Method | Purpose | Safe | Idempotent | Body |
|---|---|---|---|---|
GET | Read a resource | ✓ | ✓ | No |
HEAD | Like GET, headers only | ✓ | ✓ | No |
POST | Create, or trigger processing | ✗ | ✗ | Yes |
PUT | Replace a resource entirely | ✗ | ✓ | Yes |
PATCH | Partially modify | ✗ | ✗ (can be made so) | Yes |
DELETE | Remove | ✗ | ✓ | Rarely |
OPTIONS | Ask what's allowed (CORS preflight) | ✓ | ✓ | No |
Safe = no side effects (so crawlers and prefetchers may call it freely). Idempotent = repeating it has the same effect as doing it once, so it's safe to retry after a timeout. That's why retrying a POST payment is dangerous without an idempotency key.
Status codes
| Range | Meaning | Common codes |
|---|---|---|
| 1xx | Informational | 101 Switching Protocols (WebSocket), 103 Early Hints |
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirection | 301 Moved Permanently, 302/307 temporary, 304 Not Modified |
| 4xx | Client error | 400 Bad Request, 401 Unauthenticated, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable, 429 Too Many Requests |
| 5xx | Server error | 500 Internal Error, 502 Bad Gateway, 503 Unavailable, 504 Gateway Timeout |
Important headers
| Header | Purpose |
|---|---|
Host | Which site (many sites share one IP) — required in HTTP/1.1 |
Content-Type / Accept | Body format sent / formats wanted (application/json) |
Content-Length / Transfer-Encoding: chunked | Body size, or streamed in chunks |
Authorization | Credentials (Bearer <token>, Basic …) |
Cookie / Set-Cookie | Client state |
Cache-Control, ETag, Last-Modified | Caching |
Location | Redirect target, or the URL of a created resource |
Accept-Encoding / Content-Encoding | Compression (gzip, br, zstd) |
X-Forwarded-For / Forwarded | Original client IP behind proxies |
Caching
HTTP caching happens in browsers, CDNs and proxies.
Cache-Control: max-age=31536000, immutable— cache for a year without revalidating (for versioned assets likeapp.3f9a1c.js).Cache-Control: no-cache— may store, but must revalidate every time. (no-storemeans never store.)private(only the browser may cache) vspublic(shared caches like CDNs may too).- Conditional requests: the client sends
If-None-Match: "a1b2c3"; if unchanged, the server replies 304 Not Modified with no body.
Cookies and state
HTTP is stateless: each request stands alone. Cookies add state:
Set-Cookie: session=abc123; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=86400HttpOnly— JavaScript can't read it (limits XSS damage).Secure— sent only over HTTPS.SameSite=Lax/Strict— not sent on cross-site requests, which blocks most CSRF.
More in Authentication and Web security.
CORS
Browsers block JavaScript from reading responses from a different origin (scheme + host + port) unless the server allows it with CORS headers:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type, Authorization"Non-simple" requests (JSON bodies, custom headers, PUT/DELETE) trigger a preflight OPTIONS request first. CORS is enforced by browsers only: it protects users, not your API. curl and servers ignore it.
HTTP versions
| Version | Year | Key ideas | Limitation |
|---|---|---|---|
| HTTP/1.0 | 1996 | One request per TCP connection | Connection setup for every resource |
| HTTP/1.1 | 1997 | Keep-alive (reuse connections), Host, chunked transfer | One request at a time per connection → browsers open ~6 connections per host |
| HTTP/2 | 2015 | Binary framing, multiplexing many streams on one connection, header compression (HPACK), prioritisation | TCP head-of-line blocking |
| HTTP/3 | 2022 | HTTP/2's ideas over QUIC (UDP); independent streams, faster handshakes, connection migration | UDP sometimes blocked; more CPU |
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(5)).build();
HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.example.com/users/42"))
.header("Accept", "application/json").build();
HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(res.statusCode() + " " + res.body());import httpx # or requests
with httpx.Client(http2=True, timeout=5.0) as client:
r = client.get("https://api.example.com/users/42", headers={"Accept": "application/json"})
r.raise_for_status()
print(r.json())const res = await fetch("https://api.example.com/users/42", {
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const user = await res.json();- HTTP is stateless request–response: method + path + headers + body → status + headers + body.
- GET/PUT/DELETE are idempotent; POST isn't — use idempotency keys for safe retries.
- 4xx = client's fault, 5xx = server's fault; know 200/201/204/301/304/400/401/403/404/429/500/502/503/504.
- Cache-Control, ETags and 304s make the web fast; cookies add state (HttpOnly, Secure, SameSite).
- CORS is a browser-enforced relaxation of the same-origin policy.
- HTTP/2 multiplexes over TCP; HTTP/3 moves to QUIC to remove head-of-line blocking.
QWhat's the difference between PUT and PATCH?easy
PUT replaces the entire resource with the request body and is idempotent. PATCH applies a partial modification; whether it's idempotent depends on the patch format (a JSON Merge Patch setting fields is; "increment by 1" isn't).
QIs HTTP stateless? Then how do logins work?easy
Each request is independent at the protocol level. State is carried explicitly: a session cookie referencing server-side session data, or a self-contained token (such as a JWT) sent with every request.