Skip to content

Lesson 7 of 18How software works

HTTP and APIs

Read and write HTTP requests, pick the right method and status code, use curl, caching and auth headers, and call a JSON API safely.

30 min read0/8 questions

Almost every app you build will talk HTTP. A React page loading your profile, a FastAPI backend answering it, a payment provider confirming a charge: all HTTP. Once you can read a request and a response, debugging becomes much easier, because you can see exactly what one side asked for and what the other side said. Interviewers also love "what is the difference between PUT and PATCH?" and "401 or 403?".

A request and a response are just text

HTTP (hypertext transfer protocol) is a set of rules for a client to ask a server for something. Under the encryption, a request really is a few lines of text:

POST /api/todos HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOi...
 
{"title": "Learn HTTP", "done": false}

The first line has the method (POST), the path (/api/todos) and the protocol version. Then come headers, one Name: value per line, carrying extra information about the request. After a blank line comes the optional body, the actual data being sent.

The response has the same shape, with a status code on the first line:

HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/todos/7
 
{"id": 7, "title": "Learn HTTP", "done": false}
Create a todo, then read it back
BrowserAPI serverDatabasePOST /api/todos {title}INSERT todonew id = 7201 Created {id: 7}GET /api/todos/7200 OK {id: 7, ...}

The body holds the new todo as JSON

1/6

APIs, REST and JSON

An API (application programming interface) is a way for one program to use another. A web API is a server that answers HTTP requests with data instead of web pages, so other programs (your frontend, a mobile app, someone else's backend) can use it.

The data is almost always JSON (JavaScript object notation): text that looks like JavaScript objects and lists. Every language can read and write it.

{ "id": 7, "title": "Learn HTTP", "done": false, "tags": ["web", "basics"] }

Most web APIs follow a style called REST. The idea: your data is a set of resources (todos, users, orders), each with a URL, and you use the HTTP method to say what to do with it.

MethodMeaningExampleTypical success
GETReadGET /todos/7200 OK
POSTCreate a new onePOST /todos201 Created
PUTReplace it completelyPUT /todos/7200 OK
PATCHChange some fieldsPATCH /todos/7200 OK
DELETERemove itDELETE /todos/7204 No Content

Notice the URLs are nouns (/todos/7), and the method is the verb. A REST API does not have /getTodo or /deleteTodo.

Quick check
A todo is {title: "Buy milk", done: false}. You want to mark it done and leave the title alone, sending only {done: true}. Which method fits?
Need a nudge? A hint rules out a wrong answer.

Query strings vs bodies

There are two places to put data in a request:

  • The query string goes in the URL after ?: GET /products?category=shoes&sort=price. Use it for reading: filters, search terms, sorting, page numbers. It shows up in browser history and server logs, so never put passwords there.
  • The body goes after the headers. Use it for sending data to create or change something, with POST, PUT and PATCH. GET requests do not have a body.
ChallengeEasy

Parse a query string

A query string is the part of a URL after ?, like q=shoes&size=42. Write a function that turns one into a dictionary (Python) or object (TypeScript) of keys to string values.

"q=shoes&size=42"     →  {"q": "shoes", "size": "42"}
"name=Ada+Lovelace"   →  {"name": "Ada Lovelace"}
""                    →  {}

Rules:

  • Pairs are separated by &. Skip empty pieces (from a=1&&b=2).
  • Split each pair at the first =. A key with no = gets the value "".
  • Decode the text: + means a space, and %20-style codes are decoded (%26 is &). In Python use urllib.parse.unquote_plus; in TypeScript replace + with a space, then call decodeURIComponent.
  • If a key appears twice, the last one wins.
  • Values stay strings, even "42".
from urllib.parse import unquote_plus def parse_query(qs: str) -> dict[str, str]: # Split on &, then on the first = pass

Status codes by family

The first digit of the status code tells you the family. You only need to memorise about a dozen individual codes.

FamilyMeaningCodes you will see
1xxInformational, keep going101 Switching Protocols (WebSockets)
2xxSuccess200 OK, 201 Created, 204 No Content
3xxRedirect, look elsewhere301 Moved Permanently, 302 Found, 304 Not Modified
4xxClient error: the request was wrong400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable, 429 Too Many Requests
5xxServer error: the server failed500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable

The 4xx/5xx split matters when debugging. A 4xx means "fix your request". A 5xx means "the server broke", so look at the server's logs.

Two codes everyone mixes up: 401 means "I do not know who you are" (you are not logged in, or your token expired). 403 means "I know who you are, and you are not allowed".

Match the pairs0/6 matched

Match each situation to its status code.

Choose an item, then its match on the other side.
ChallengeEasy

Name the status code family

Every HTTP response has a three-digit status code, and the first digit tells you the family. Write a function that names it.

CodesReturn
100–199"informational"
200–299"success"
300–399"redirect"
400–499"client error"
500–599"server error"
anything else"unknown"
200  →  "success"
404  →  "client error"
503  →  "server error"
def status_family(code: int) -> str: # The first digit decides the family. pass

Headers, cookies and tokens

Headers carry information about the request or response. A few you will meet constantly:

HeaderWhat it says
Content-Type: application/jsonThe body is JSON
Accept: application/jsonThe client would like JSON back
Authorization: Bearer <token>Here is proof of who I am
Cookie / Set-CookieSmall values the browser stores and sends back automatically
Cache-Control: max-age=3600You may reuse this response for an hour

HTTP itself has no memory: every request stands alone. So how does a site know you are logged in? There are two common answers:

  • Cookies. After you log in, the server sends Set-Cookie: session=abc123. The browser stores it and attaches it automatically to every later request to that site. The server looks up abc123 to find your account.
  • Tokens. The server gives the client a token (often a JWT, JSON web token: a signed piece of JSON). The client stores it and sends it in the Authorization header itself. This is common for mobile apps and APIs used by other programs.

Both are fine. The details (and the security trade-offs) come in the FastAPI and Next.js tracks.

Idempotency: safe to retry?

Networks fail. If a request times out, can the client simply send it again? That depends on whether the method is idempotent: doing it twice has the same effect as doing it once.

  • GET, PUT and DELETE are idempotent. Reading twice changes nothing. Replacing a todo with the same content twice leaves the same todo. Deleting twice still leaves it deleted (the second call may return 404, but the data is in the same state).
  • POST is not idempotent. Sending "create an order" twice can create two orders, and charge someone twice.

That is why payment APIs ask you to send an idempotency key, a unique ID per action, so the server can spot a retry and ignore the duplicate.

Quick check
Your app's request timed out and you do not know if the server received it. Which one is risky to retry blindly?
Need a nudge? A hint rules out a wrong answer.

Safe, idempotent, cacheable: the methods in full

Interviewers like this table because it tests whether you know why each method exists, not just its name. Two properties matter:

  • Safe: the request does not change anything on the server. Browsers, crawlers and link previews send safe requests freely, so a GET that deletes data will eventually be triggered by a bot.
  • Idempotent: repeating it leaves the server in the same state as doing it once. Proxies, client libraries and you are all allowed to retry idempotent requests after a timeout.
MethodSafeIdempotentBodyTypical use
GETyesyesnoRead a resource or a list
HEADyesyesnoLike GET but headers only: does it exist, how big is it?
OPTIONSyesyesnoWhich methods are allowed? Browsers send it as the CORS "preflight"
POSTnonoyesCreate, or any action that is not a simple update
PUTnoyesyesReplace the resource at this exact URL, or create it there
PATCHnonot guaranteedyesChange some fields
DELETEnoyesoptionalRemove it

Three details catch people out:

  • PUT can create. PUT /users/42/avatar with an image creates it if missing and replaces it otherwise. The client chooses the URL. With POST /todos the server chooses the new ID.
  • PATCH is not automatically idempotent. {"done": true} is, since sending it twice gives the same result. But {"op": "increment", "field": "views"} adds one each time. Whether a PATCH is safe to retry depends on how the API designed it.
  • Idempotent is about server state, not the response. A second DELETE /todos/7 may return 404 instead of 204, and it is still idempotent, because the todo is gone either way.

POST can be made retry-safe with the idempotency key you saw above: the client sends a unique Idempotency-Key header, and the server stores the result under that key so a repeat returns the stored result instead of acting twice.

Quick check
A mobile app retries any request that times out. Which request is risky to retry automatically?
Need a nudge? A hint rules out a wrong answer.

curl: HTTP from the terminal

curl is how engineers talk to an API without writing code: to check an endpoint works, reproduce a bug, or share an exact request in a ticket. It ships with macOS, nearly every Linux system and Windows 10 and later. These are the flags you will use every week:

FlagDoes
-iShow the response status line and headers, then the body
-X PATCHSet the method (GET is the default; -d switches to POST)
-H 'Name: value'Add a request header
-d 'data'Send a body. Defaults to form encoding, not JSON
--json '{...}'Send JSON and set the Content-Type and Accept headers for you
-s / -SSilent (no progress bar) / but still show errors
-o fileWrite the body to a file (-o /dev/null to discard it)
--fail-with-bodyExit non-zero on a 4xx or 5xx, so scripts notice failures
-vVerbose: every stage of the connection

Here they are against httpbin.org, a free test service that echoes back what it received. The output is real, trimmed:

curl --json '{"title": "Learn HTTP"}' https://httpbin.org/post# "headers": { "Accept": "application/json", "Content-Type": "application/json", ... }# "json": { "title": "Learn HTTP" }curl -X PATCH https://httpbin.org/anything \  -H 'Authorization: Bearer abc123' \  -H 'Content-Type: application/json' \  -d '{"done": true}'# "method": "PATCH"curl -s -o /dev/null -w '%{http_code}\n' https://httpbin.org/status/404# 404

Two traps. First, curl exits 0 on a 404 or 500, just like fetch does not throw: the HTTP exchange worked. Add --fail-with-body in scripts and CI, and curl exits 22 on an error status while still printing the body. Second, -d alone sends Content-Type: application/x-www-form-urlencoded, so many JSON APIs reject it with a 400 or 415. Use --json (curl 7.82 and later) or add the header yourself.

On Windows, type curl.exe, not curl. In the older Windows PowerShell 5.1, curl is an alias for Invoke-WebRequest, which takes completely different options. Quoting JSON for curl.exe also differs between PowerShell versions, which is why the PowerShell examples use Invoke-RestMethod for JSON bodies. Inside WSL, curl works exactly as on Linux.

To read every stage of a connection with -v (DNS, TCP, TLS, then the request), see Networking You Will Actually Debug. And a useful habit: the browser's Network tab can copy any request as a curl command (right-click, Copy as cURL), so you can replay what the frontend sent, tweak one header, and see what changes.

Caching headers: Cache-Control and ETag

The fastest request is the one never sent. HTTP has caching built in, and two families of headers control it.

Cache-Control on a response says who may store it and for how long:

DirectiveMeans
max-age=3600Fresh for 3600 seconds. Reuse it without asking the server
no-cacheYou may store it, but must check with the server before each use
no-storeNever store it anywhere. For sensitive data like bank statements
privateOnly the user's browser may store it, not a shared cache or CDN
publicShared caches such as CDNs may store it too
immutableIt will never change, so do not even revalidate

no-cache is the most misread header in HTTP: it does not mean "do not cache". no-store does. Build tools give static files names with a content hash, like app.3f9a1c.js, so they can be served with max-age=31536000, immutable: a new version gets a new name, and the old one may be cached forever. The HTML page that references them gets a short or zero max-age so users pick up new deploys.

When something is stale or marked no-cache, the browser does not have to download it again. It can revalidate. The server sends an ETag, a fingerprint of the content, and the client sends it back in If-None-Match. If nothing changed, the server replies 304 Not Modified with no body:

Revalidating with an ETag
BrowserServerGET /api/products200 + ETag: "v7" + 80 KB bodyGET + If-None-Match: "v7"304 Not Modified, no bodyGET + If-None-Match: "v7"200 + ETag: "v8" + new body

First visit: nothing in the cache.

1/6

You can watch this with curl against httpbin's test endpoint, which uses the ETag you give it:

curl -si https://httpbin.org/etag/abc123 | head -1# HTTP/2 200curl -si -H 'If-None-Match: "abc123"' https://httpbin.org/etag/abc123 | head -1# HTTP/2 304

A server side of this is only a few lines. Run it and change the product list:

Python
import hashlib, json products = [{"id": 1, "name": "Mug", "price": 12}] def handle_get(if_none_match=None): body = json.dumps(products) etag = '"' + hashlib.sha256(body.encode()).hexdigest()[:8] + '"' if if_none_match == etag: return 304, etag, "" return 200, etag, body status, etag, body = handle_get()print(status, etag, len(body), "bytes") status, etag, body = handle_get(if_none_match=etag)print(status, etag, len(body), "bytes") products[0]["price"] = 15 # the data changesstatus, etag, body = handle_get(if_none_match=etag)print(status, etag, len(body), "bytes")
Output
Press Run (⌘ Enter) to see what happens.

Notice the server still builds the response to compute the ETag, so a 304 saves bandwidth, not the work of producing the data. Saving that work is what server-side caches (covered in the backend tracks) are for. An older pair of headers, Last-Modified and If-Modified-Since, does the same with timestamps.

Quick check
Your API returns account balances. You want browsers and CDNs to never keep a copy. Which header is right?
Need a nudge? A hint rules out a wrong answer.

Auth schemes at a glance

Every API you call will ask you to prove who you are in one of a handful of ways. You do not need to implement them yet, but you need to recognise each one on sight:

SchemeWhat travels on each requestTypical use
API keyX-API-Key: sk_live_... or Authorization: Bearer sk_...Server-to-server calls to a provider like a payment or email API
Basic authAuthorization: Basic <base64 of user:password>Internal tools, package registries. Only ever over HTTPS
Session cookieCookie: session=abc123, sent by the browser automaticallyClassic web apps with a login form
Bearer token (often a JWT)Authorization: Bearer eyJhbGciOi...SPAs, mobile apps, APIs between services
OAuth 2.0A bearer token, obtained by a redirect flow"Sign in with Google", or letting an app access your GitHub

Basic auth and JWTs share a trap: base64 is encoding, not encryption. Anyone who sees the header can decode it. A JWT's middle section is readable JSON; the signature only proves nobody changed it. Run this to see both halves:

Python
import base64, hashlib, hmac, json def b64url(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode() def unb64url(text: str) -> bytes: return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) SECRET = b"server-only-secret" def sign(payload: dict) -> str: head = b64url(json.dumps({"alg": "HS256", "typ": "JWT"}).encode()) body = b64url(json.dumps(payload).encode()) sig = hmac.new(SECRET, f"{head}.{body}".encode(), hashlib.sha256).digest() return f"{head}.{body}.{b64url(sig)}" def verify(token: str) -> bool: head, body, sig = token.split(".") expected = hmac.new(SECRET, f"{head}.{body}".encode(), hashlib.sha256).digest() return hmac.compare_digest(expected, unb64url(sig)) token = sign({"sub": "42", "role": "user"})print(token)print("anyone can read:", json.loads(unb64url(token.split(".")[1])))print("valid:", verify(token)) head, body, sig = token.split(".")forged = b64url(json.dumps({"sub": "42", "role": "admin"}).encode())print("forged valid:", verify(f"{head}.{forged}.{sig}"))
Output
Press Run (⌘ Enter) to see what happens.

So never put secrets in a JWT payload, and always verify the signature on the server. Cookies have their own protections, set by the server: HttpOnly (JavaScript cannot read it, so an XSS bug cannot steal it), Secure (HTTPS only) and SameSite (not sent on most cross-site requests).

OAuth 2.0 solves a different problem: letting an app act on your behalf at another service without ever seeing your password. The common version for web and mobile apps is the authorization code flow with PKCE:

Sign in with GitHub (authorization code flow)
BrowserYour appGitHubclick Sign in with GitHubredirect to github.com/login/oauth/authorizelog in, approve scopesredirect back with ?code=...GET /callback?code=...exchange code for tokenaccess token

click Sign in with GitHub

1/7

The short-lived code travels through the browser, but the token is fetched server to server, which is the point of the design. Implementing OAuth yourself is rarely a good idea; use your framework's library or an auth provider, and check the provider's official docs for the exact parameters.

Put it in order5 steps

Put the authorization code flow in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Pagination and rate limits

Real APIs never return a million rows in one response, and they never let one client send unlimited requests. Your code has to handle both.

Pagination splits a list into pages. There are two common styles:

  • Offset: GET /orders?offset=100&limit=50, or ?page=3&per_page=50. Simple, and lets you jump to page 40. But if new orders arrive while you page through, everything shifts, so you skip or repeat items, and large offsets are slow for the database to compute.
  • Cursor: GET /orders?limit=50&cursor=eyJpZCI6MTUwfQ. Each response includes a next_cursor (often an encoded "last ID I gave you"), and you pass it back for the next page. Stable while data changes and fast at any depth, but you can only go forward. Large APIs like Stripe's and Slack's use cursors.

Either way the loop is the same: request a page, process it, and stop when there is no next page. Some APIs, like GitHub's, put the next page's URL in a Link response header instead of the body.

Rate limits cap how many requests you may send in a window. Go over and you get 429 Too Many Requests, often with a Retry-After header saying how many seconds to wait (it can also be a date). Many APIs also send headers such as X-RateLimit-Remaining; the names vary, so check the provider's docs.

The correct client behaviour is to wait and retry, but not in a tight loop and not all at once. If Retry-After is present, honour it. Otherwise use exponential backoff: wait 0.5 s, then 1, 2, 4, up to a cap, and add random jitter so a thousand clients that failed together do not all retry in the same millisecond. Only retry what is safe: 429, 503 and network timeouts on idempotent requests, never a 400.

This simulation runs instantly because it records the waits instead of sleeping:

Python
import random random.seed(1)responses = [(429, {"Retry-After": "2"}), (503, {}), (503, {}), (200, {})] def call_api(): return responses.pop(0) def get_with_retry(max_attempts=5, base=0.5, cap=30): for attempt in range(max_attempts): status, headers = call_api() if status < 400: return status if status not in (429, 503): raise RuntimeError(f"not retryable: {status}") if "Retry-After" in headers: wait = float(headers["Retry-After"]) else: wait = random.uniform(0, min(cap, base * 2 ** attempt)) # full jitter print(f"attempt {attempt + 1}: {status}, waiting {wait:.2f}s") raise RuntimeError("gave up") print("final status:", get_with_retry())
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

Without jitter, what delays does this backoff schedule produce?

print([min(30, 0.5 * 2 ** a) for a in range(7)])
Need a nudge? Hints walk you through it.

Calling an API with fetch

In JavaScript, you make HTTP requests with fetch. It returns a Promise (a value that arrives later), so you use await to wait for it. The code windows here cannot reach real servers, but fetch works with two built-in classes you can use offline: Request and Response. Run this to see what a request and a response contain:

JavaScriptrequest-response.js
const request = new Request("https://api.example.com/todos?done=false", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer abc123" }, body: JSON.stringify({ title: "Learn HTTP", done: false }),});console.log(request.method, request.url);console.log(request.headers.get("content-type"));console.log(await request.text()); const response = new Response('{"id": 7, "title": "Learn HTTP", "done": false}', { status: 201, headers: { "Content-Type": "application/json" },});console.log(response.status, response.ok);const todo = await response.json();console.log(todo.id, todo.title);
Output
Press Run (⌘ Enter) to see what happens.

JSON.stringify turns an object into JSON text for the body, and response.json() parses the JSON text back into an object. response.ok is true for any 2xx status.

Here is the pattern you will write a hundred times. The fakeFetch function stands in for the real fetch so it runs offline:

JavaScriptload-todo.js
async function fakeFetch(url, options = {}) { console.log("->", options.method ?? "GET", url); if (url.endsWith("/todos/1")) { return new Response(JSON.stringify({ id: 1, title: "Buy milk", done: true }), { status: 200 }); } return new Response(JSON.stringify({ error: "Not found" }), { status: 404 });} async function loadTodo(id) { const res = await fakeFetch(`https://api.example.com/todos/${id}`); if (!res.ok) { console.log("Request failed with status", res.status); return null; } return res.json();} console.log(await loadTodo(1));console.log(await loadTodo(99));
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputJavaScript

What does this print?

const res = new Response("{}", { status: 404 });
console.log(res.ok);
Need a nudge? Hints walk you through it.

Python reads and writes JSON with the built-in json module:

Python
import json text = '{"id": 7, "title": "Learn HTTP", "done": false, "tags": ["web"]}'todo = json.loads(text) # JSON text -> Python dictprint(todo["title"], todo["done"]) todo["done"] = Trueprint(json.dumps(todo)) # Python dict -> JSON text
Output
Press Run (⌘ Enter) to see what happens.

Notice JSON's false became Python's False and back again.

CORS in one paragraph

Browsers protect you with the same-origin policy: JavaScript on site-a.com cannot read responses from api.site-b.com, because otherwise any page you visit could quietly read your email from another tab. An origin is the scheme, host and port together. CORS (cross-origin resource sharing) is how a server opts in: it sends a header like Access-Control-Allow-Origin: https://site-a.com to say "that site may read my responses". When you see a CORS error in the browser console, the fix is almost always on the server, not in your frontend code. Tools like curl and backend code ignore CORS entirely, because it is a browser rule.

Key terms
HTTP method
The verb of a request: GET reads, POST creates, PUT replaces, PATCH updates, DELETE removes.
status code
Three digits on a response. 2xx success, 3xx redirect, 4xx client error, 5xx server error.
REST
An API style where URLs name resources (nouns) and HTTP methods say what to do with them.
JSON
A text format for data with objects, arrays, strings, numbers, booleans and null. The standard for web APIs.
idempotent
Doing it twice has the same effect as doing it once. GET, PUT and DELETE are; POST is not.
CORS
Headers a server sends to let JavaScript from another origin read its responses in a browser.
safe method
A method that must not change server state: GET, HEAD and OPTIONS.
ETag
A fingerprint of a response. Sent back in If-None-Match, it lets the server reply 304 Not Modified with no body.
OAuth 2.0
A redirect-based flow that gives an app a token to act for a user at another service, without seeing their password.
exponential backoff
Retrying with doubling waits up to a cap, plus random jitter, after 429s, 503s or timeouts.