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.
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}The body holds the new todo as JSON
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.
| Method | Meaning | Example | Typical success |
|---|---|---|---|
GET | Read | GET /todos/7 | 200 OK |
POST | Create a new one | POST /todos | 201 Created |
PUT | Replace it completely | PUT /todos/7 | 200 OK |
PATCH | Change some fields | PATCH /todos/7 | 200 OK |
DELETE | Remove it | DELETE /todos/7 | 204 No Content |
Notice the URLs are nouns (/todos/7), and the method is the verb. A REST API does not have /getTodo or /deleteTodo.
{title: "Buy milk", done: false}. You want to mark it done and leave the title alone, sending only {done: true}. Which method fits?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,PUTandPATCH.GETrequests do not have a body.
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 (froma=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 (%26is&). In Python useurllib.parse.unquote_plus; in TypeScript replace+with a space, then calldecodeURIComponent. - If a key appears twice, the last one wins.
- Values stay strings, even
"42".
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.
| Family | Meaning | Codes you will see |
|---|---|---|
| 1xx | Informational, keep going | 101 Switching Protocols (WebSockets) |
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirect, look elsewhere | 301 Moved Permanently, 302 Found, 304 Not Modified |
| 4xx | Client error: the request was wrong | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable, 429 Too Many Requests |
| 5xx | Server error: the server failed | 500 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 each situation to its status code.
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.
| Codes | Return |
|---|---|
| 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"Headers, cookies and tokens
Headers carry information about the request or response. A few you will meet constantly:
| Header | What it says |
|---|---|
Content-Type: application/json | The body is JSON |
Accept: application/json | The client would like JSON back |
Authorization: Bearer <token> | Here is proof of who I am |
Cookie / Set-Cookie | Small values the browser stores and sends back automatically |
Cache-Control: max-age=3600 | You 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 upabc123to 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
Authorizationheader 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,PUTandDELETEare 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).POSTis 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.
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
GETthat 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.
| Method | Safe | Idempotent | Body | Typical use |
|---|---|---|---|---|
GET | yes | yes | no | Read a resource or a list |
HEAD | yes | yes | no | Like GET but headers only: does it exist, how big is it? |
OPTIONS | yes | yes | no | Which methods are allowed? Browsers send it as the CORS "preflight" |
POST | no | no | yes | Create, or any action that is not a simple update |
PUT | no | yes | yes | Replace the resource at this exact URL, or create it there |
PATCH | no | not guaranteed | yes | Change some fields |
DELETE | no | yes | optional | Remove it |
Three details catch people out:
- PUT can create.
PUT /users/42/avatarwith an image creates it if missing and replaces it otherwise. The client chooses the URL. WithPOST /todosthe 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/7may 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.
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:
| Flag | Does |
|---|---|
-i | Show the response status line and headers, then the body |
-X PATCH | Set 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 / -S | Silent (no progress bar) / but still show errors |
-o file | Write the body to a file (-o /dev/null to discard it) |
--fail-with-body | Exit non-zero on a 4xx or 5xx, so scripts notice failures |
-v | Verbose: 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# 404Two 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:
| Directive | Means |
|---|---|
max-age=3600 | Fresh for 3600 seconds. Reuse it without asking the server |
no-cache | You may store it, but must check with the server before each use |
no-store | Never store it anywhere. For sensitive data like bank statements |
private | Only the user's browser may store it, not a shared cache or CDN |
public | Shared caches such as CDNs may store it too |
immutable | It 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:
First visit: nothing in the cache.
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 304A server side of this is only a few lines. Run it and change the product list:
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.
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:
| Scheme | What travels on each request | Typical use |
|---|---|---|
| API key | X-API-Key: sk_live_... or Authorization: Bearer sk_... | Server-to-server calls to a provider like a payment or email API |
| Basic auth | Authorization: Basic <base64 of user:password> | Internal tools, package registries. Only ever over HTTPS |
| Session cookie | Cookie: session=abc123, sent by the browser automatically | Classic web apps with a login form |
| Bearer token (often a JWT) | Authorization: Bearer eyJhbGciOi... | SPAs, mobile apps, APIs between services |
| OAuth 2.0 | A 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:
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:
click Sign in with GitHub
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 the authorization code flow in order.
- Tap the steps below in the right order.
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 anext_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:
Press Run (⌘ Enter) to see what happens.Without jitter, what delays does this backoff schedule produce?
print([min(30, 0.5 * 2 ** a) for a in range(7)])
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:
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:
Press Run (⌘ Enter) to see what happens.What does this print?
const res = new Response("{}", { status: 404 });
console.log(res.ok);Python reads and writes JSON with the built-in json module:
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.
- 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.