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.

Intermediate 5 min readLesson 10 of 15 Interview Q&A

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

HTTP
GET /api/users/42?fields=name HTTP/1.1
Host: api.example.com
Accept: application/json
Authorization: Bearer eyJhbGciOi...
User-Agent: curl/8.4.0
HTTP
HTTP/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

MethodPurposeSafeIdempotentBody
GETRead a resource✓✓No
HEADLike GET, headers only✓✓No
POSTCreate, or trigger processing✗✗Yes
PUTReplace a resource entirely✗✓Yes
PATCHPartially modify✗✗ (can be made so)Yes
DELETERemove✗✓Rarely
OPTIONSAsk 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

RangeMeaningCommon codes
1xxInformational101 Switching Protocols (WebSocket), 103 Early Hints
2xxSuccess200 OK, 201 Created, 204 No Content
3xxRedirection301 Moved Permanently, 302/307 temporary, 304 Not Modified
4xxClient error400 Bad Request, 401 Unauthenticated, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable, 429 Too Many Requests
5xxServer error500 Internal Error, 502 Bad Gateway, 503 Unavailable, 504 Gateway Timeout

Important headers

HeaderPurpose
HostWhich site (many sites share one IP) — required in HTTP/1.1
Content-Type / AcceptBody format sent / formats wanted (application/json)
Content-Length / Transfer-Encoding: chunkedBody size, or streamed in chunks
AuthorizationCredentials (Bearer <token>, Basic …)
Cookie / Set-CookieClient state
Cache-Control, ETag, Last-ModifiedCaching
LocationRedirect target, or the URL of a created resource
Accept-Encoding / Content-EncodingCompression (gzip, br, zstd)
X-Forwarded-For / ForwardedOriginal 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 like app.3f9a1c.js).
  • Cache-Control: no-cache — may store, but must revalidate every time. (no-store means never store.)
  • private (only the browser may cache) vs public (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:

HTTP
Set-Cookie: session=abc123; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=86400
  • HttpOnly — 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:

HTTP
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

VersionYearKey ideasLimitation
HTTP/1.01996One request per TCP connectionConnection setup for every resource
HTTP/1.11997Keep-alive (reuse connections), Host, chunked transferOne request at a time per connection → browsers open ~6 connections per host
HTTP/22015Binary framing, multiplexing many streams on one connection, header compression (HPACK), prioritisationTCP head-of-line blocking
HTTP/32022HTTP/2's ideas over QUIC (UDP); independent streams, faster handshakes, connection migrationUDP 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());
Key takeaways
  • 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.
Interview questions
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.