Computing Foundations › How the Internet Works › Day 18
Day 18: HTTP: Requests, Responses, and Methods
After this lesson you will be able to read a raw HTTP request and response, choose the right method, and interpret status codes — so that when a call to a hosted model fails, you can tell a 401 from a 429 from a 500 and know exactly what to do.
Hands-on lab for this lesson
Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/computing-foundations/day-018-http-requests-responses-and-methods
- Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git cd ai-roadmap-365.github.io - Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
cd labs/sections/computing-foundations/day-018-http-requests-responses-and-methods - Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
- Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
bash tests/run_tests.sh # or the test command named in the lab README
You can also open the lab as a local page (works offline, shows the file tree and expected output).
Learning objectives
By the end of this lesson you will be able to:
- Name and explain the four parts of an HTTP request (method, path, headers, body) and the three parts of a response (status line, headers, body)
- Choose the correct HTTP method for a task and explain what safe and idempotent mean for GET, POST, PUT, PATCH, and DELETE
- Classify status codes by their 1xx-5xx class and recall what the important codes (200, 201, 204, 301/302, 304, 400, 401, 403, 404, 429, 500, 502, 503) signal
- Identify the headers that matter most — Content-Type, Accept, Authorization, User-Agent, Cache-Control, Content-Length — and say what each controls
- Explain HTTP statelessness and how cookies and session IDs create the feeling of a continuous session on top of it
- Use curl (verbose, status-only, and POST-with-body), browser DevTools, and HTTPie to send real requests and read the raw responses
- Connect the protocol to AI practice: describe why every hosted-model call is an HTTP POST with a JSON body and an Authorization header, and how reading status codes debugs auth and rate-limit failures
Prerequisites
- Day 8-14 shell skills: running commands in a terminal and reading their output
- A basic idea that computers talk over a network (no networking theory required — this lesson builds it)
- A computer running macOS or Linux with curl (preinstalled) and internet access
Why this matters
-
Every model API call is an HTTP POST, and reading the request and response is the whole debugging skill.
-
401and429will be your two most frequent AI errors — a bad key and too many requests — and both are readable at a glance. -
POSTis not idempotent, which means a naive retry can charge you twice for the same generation. -
Everything you build will speak HTTP, whether you write the client or the server.
-
The protocol is plain text. You can type it by hand, and today you will.
The idea in plain language
-
HTTP is two messages: a request and a response. Everything else is variation.
-
Both have the same shape: a first line, some headers, a blank line, then an optional body.
-
The method is your verb — what you intend: read, create, replace, remove.
-
The status code is the verdict, and its first digit tells you whose fault it is.
-
HTTP is stateless. The server forgets you the moment it answers, which is why every request must carry its own identity.
Historical background
-
HTTP 0.9, 1991, was one line:
GET /page. No headers, no status codes, no methods but one. -
HTTP/1.0, 1996, added headers, status codes and methods, which is most of what you still use.
-
HTTP/1.1, 1997, added persistent connections and the
Hostheader — the latter is what let one server host many sites, and so made shared hosting possible. -
HTTP/2, 2015, kept the semantics and changed the encoding to binary, with multiplexing.
-
HTTP/3 moved to QUIC, as Day 17 described.
-
The semantics have barely changed since 1997. A request you write today would be understood by a server from then.
What it is — and what it is not
It is:
- A request-response protocol: you ask, the server answers, the exchange ends.
- Stateless by design — each request is self-contained.
- Text-based in its semantics, whatever the wire encoding.
It is not:
-
Not a connection you hold a conversation over. The connection may be reused, but each request stands alone.
-
Not secure by itself. That is TLS, which is tomorrow.
-
Not only for browsers. Most HTTP traffic today is programs talking to programs.
-
Not stateful, even with cookies. A cookie makes each request carry the key to state the server holds elsewhere.
Why it was created and what problems it solves
-
A common language for arbitrary clients and servers. Anyone can implement it, which is why everything does.
-
Simplicity you can debug. A protocol you can type by hand is a protocol you can reason about.
-
Statelessness for scale. Any server can answer any request, which is what makes load balancing possible at all.
-
Cacheability. Because
GETis safe and idempotent, anything on the path may keep a copy. -
Extensibility through headers. Every capability added since 1997 — compression, authentication, CORS, caching rules — arrived as headers, without a new protocol.
How it works
The request message
POST /v1/messages HTTP/1.1
Host: api.example
Content-Type: application/json
Authorization: Bearer sk-secret-token
Content-Length: 27
{"prompt":"Hello, server"}
-
The request line names the method, the path, and the version.
-
Headers follow, one per line, as
Name: value. -
A single blank line is mandatory and marks where headers end and the body begins.
-
Hostsays which site on the server you want — the header that made shared hosting possible. -
Content-Lengthtells the server where the body ends.
The response message
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 41
Cache-Control: no-store
{"reply":"Hello to you too, client!"}
-
The status line carries the version, the three-digit code, and a reason phrase for humans.
-
The headers describe the response, and the body is what you asked for.
-
That is the complete round trip. Everything else in HTTP is variation on these two messages.
Methods: the verbs
| Method | Intent | Body? | Safe? | Idempotent? |
|---|---|---|---|---|
GET | Read; change nothing | No | Yes | Yes |
POST | Send data to be processed; often creates | Yes | No | No |
PUT | Replace the resource entirely | Yes | No | Yes |
PATCH | Apply a partial update | Yes | No | No |
DELETE | Remove the resource | Rarely | No | Yes |
- Safe means it only reads. Browsers and caches repeat safe requests freely.
- Idempotent means doing it twice has the same effect as doing it once.
POSTis not idempotent, which is why a flaky network plus automatic retries can create two orders — or bill you twice for one model call.
Status codes: the verdict
| Class | Meaning | You should |
|---|---|---|
1xx | Received, continue | Ignore in everyday work |
2xx | Success | Read the body |
3xx | It lives elsewhere | Follow Location |
4xx | Your request was wrong | Fix it — retrying unchanged is pointless |
5xx | The server failed | Retry with backoff; not your fault |
-
200 OK— success, body holds the answer. -
201 Created— a resource was made;Locationoften points at it. -
204 No Content— success with deliberately no body, common afterDELETE. -
301/302— permanent and temporary redirects. -
304 Not Modified— your cached copy is fine; no body sent. -
400malformed,401not authenticated,403authenticated but not allowed,404no such path. -
429 Too Many Requests— slow down;Retry-Aftermay say how long. -
500unhandled server fault,502/503a proxy could not reach the service, or it is overloaded.
Headers that matter
-
Content-Typedeclares the body’s format. Send JSON without it and many servers reject the body. -
Acceptsays which formats you can handle, letting one endpoint serve JSON to a script and HTML to a browser. -
Authorizationcarries your credential, usuallyBearer <token>. This header decides between200and401. -
Cache-Controlgoverns storage, fromno-storetomax-age=3600. -
User-Agentidentifies the client, and servers sometimes vary behaviour on it.
Cookies and statelessness
-
The server forgets you the instant it answers.
-
Set-Cookiein a response hands your client a small piece of data, often a random session ID. -
Your client returns it in a
Cookieheader on every later request. -
The real session lives in the server’s own storage, keyed by that ID.
-
So the protocol stays stateless while the experience feels continuous.
-
Model APIs skip cookies and put a long-lived token in
Authorizationinstead — the same idea, simpler.
The versions
-
HTTP/1.1 is text, one request at a time per connection. Its weakness is head-of-line blocking: a slow response holds up everything behind it.
-
HTTP/2 keeps identical methods, headers and codes, encodes them in binary, and multiplexes many exchanges over one connection.
-
HTTP/3 keeps HTTP/2’s model on QUIC, removing the last blocking and setting up faster on flaky networks.
-
The mental model is identical across all three, and your tools negotiate the version for you.
An everyday analogy
A formal letter and its reply.
| The post | HTTP |
|---|---|
| ”Please send me…” | The method |
| The address on the envelope | The path |
| The letterhead | The headers |
| The blank line before the text | The header/body boundary |
| The enclosure | The body |
| ”Approved” or “Rejected: incomplete” | The status code |
| A reference number to quote next time | A cookie |
-
The clerk answering has no memory of you. Everything they need is in this letter, which is what stateless means.
-
The reference number is how continuity is faked. Quote it and they can look up your file.
Examples in practice
-
401on every call: the key is missing, malformed, or in the wrong header. Retrying will never help. -
429withRetry-After: 20: you are being rate-limited and told exactly how long to wait. -
400with a JSON body explaining what was wrong: read it. Most APIs say precisely which field failed. -
502from a gateway: something in front could not reach the real service. Not your request’s fault. -
A
POSTthat times out and is retried, creating two of whatever it created.
Implications: security, privacy, performance, scalability, and cost
-
Security: the
Authorizationheader is a secret in transit. It is why HTTPS is not optional, and why a logged request can leak a key. -
Never put a token in a URL. URLs are logged by every proxy, saved in browser history, and sent in
Refererheaders. -
Privacy: headers identify you.
User-Agent,Accept-Languageand the rest form a fingerprint before any cookie is set. -
Performance:
304 Not Modifiedis free bandwidth. Conditional requests are the cheapest optimisation available and cost one header. -
Scalability: statelessness is what makes horizontal scaling possible. Any server can answer any request because none of them remembers anything.
-
Cost: retrying a non-idempotent
POSTcosts real money when the thing on the other end bills per call.
Alternatives: free, open source, and commercial
| Tool | Type | What it gives you |
|---|---|---|
curl | Free, built in | Any request you can describe, and -v shows both messages |
httpie | Free, open source | The same, with far friendlier syntax and colour |
| Browser dev tools | Bundled, free | Every request a page made, with timings |
| Postman / Insomnia | Free tiers | Saved collections, environments, sharing |
requests / httpx | Free, open source | HTTP from Python; httpx also does async |
mitmproxy | Free, open source | Watching and rewriting traffic you control |
-
Learn
curl -vbefore any GUI. It shows the raw request and response, which is what you need when something is wrong. -
Use a session object in
requestsorhttpx, or you pay Day 15’s handshake cost on every single call.
Comparison with related concepts
| Term | What it actually is |
|---|---|
| Method | The verb declaring your intent |
| Path | Which resource on the server |
| Header | Metadata as a Name: value line |
| Body | The payload, after the blank line |
| Status code | The three-digit verdict |
| Safe | Reads only; changes nothing |
| Idempotent | Twice has the same effect as once |
When to use it — and when not to
-
Retry
5xxand429; never retry4xxunchanged. The first two are transient; the third is a bug in your request. -
Retry with exponential backoff and jitter, or a thousand clients will retry in unison and finish the server off.
-
Make retried
POSTs safe with an idempotency key, if the API supports one. This is the standard fix, not a workaround. -
Use
GETonly for reads. AGETthat changes something will be triggered by a crawler, a prefetcher or a cache, eventually. -
Do not invent status codes. The registry has one for almost everything, and a novel code is a code nothing handles.
-
Do not use HTTP where you need a persistent bidirectional channel. That is WebSockets, and forcing HTTP into the role produces polling.
The AI connection
-
Every hosted model call is a
POSTwith a JSON body and a bearer token. -
429is the response you will tune your code around, andRetry-Afteris the server telling you exactly how. -
Streaming responses use server-sent events over HTTP, which is why the first token arrives long before the last.
-
Token counts arrive in response headers on many providers, which is how you measure cost without parsing the body.
-
The non-idempotent
POSTproblem is expensive here. A retried generation is a second generation, billed, and possibly a different answer.
Knowledge check
quiz:
question: "A client automatically retries any request that times out. Against a model API, this occasionally produces duplicate charges even when the original request succeeded. What property explains it?"
options:
- "POST is not idempotent, so a request that succeeded but whose response was lost is performed again"
- "The API returns 5xx errors for successful requests that exceed the timeout"
- "Bearer tokens expire mid-request, causing the server to process the call twice"
- "HTTP is stateless, so the server cannot tell two different clients apart"
answer_index: 0
explanation: "A timeout tells you the response did not arrive, not that the work did not happen. Because POST is not idempotent, repeating it does the work a second time — which is why APIs offer idempotency keys for exactly this case."
Hands-on exercise
Read both messages raw, then provoke each status class deliberately. Worked through fully in the Day 18 lab directory.
| What you are doing | Command |
|---|---|
| See the whole exchange | curl -v https://example.com |
| Headers only | curl -I https://example.com |
| Send JSON with a method | curl -X POST -H 'Content-Type: application/json' -d '{"a":1}' URL |
| Provoke a 404 | curl -i https://example.com/nope |
| Provoke a 401 | Call an authenticated endpoint with no token |
| Follow a redirect | curl -iL http://example.com |
| Time it | curl -w '%{http_code} %{time_total}\n' -o /dev/null -s URL |
Expected output
> GET / HTTP/1.1
> Host: example.com
>
< HTTP/1.1 200 OK
< Content-Type: text/html; charset=UTF-8
< Content-Length: 1256
>lines are what you sent;<lines are what came back.- The blank line after the request headers is the boundary, and it is mandatory.
Validate your work
- You can point at the request line, the headers, the blank line and the body
- You produced a
2xx, a4xxand a3xxdeliberately - You sent a JSON body with the correct
Content-Type - You explained why one of your requests returned
401rather than403 - You followed a redirect and saw both responses
-
bash tests/run_tests.shreports 0 failures
Troubleshooting
-
The server ignores your body. You omitted
Content-Type, and many servers will not guess. -
curlshows nothing useful. Add-vfor the exchange, or-ito include response headers in the output. -
A redirect returns an empty body. That is correct; add
-Lto follow it. -
Your JSON is rejected as malformed. Shell quoting. Use single quotes around the whole payload, or
--data-binary @file.json.
Common mistakes
- Retrying a
4xx. Nothing about waiting fixes a wrong request. - Putting a token in the URL rather than the
Authorizationheader. - Assuming a timeout means the work did not happen.
- Reading
403as “log in”. You already did; you are simply not allowed.
Practice assignment
-
Write out a request and response by hand on paper, from memory, then check yourself against
curl -v. -
Collect one real example of each status class from public APIs, and record what the body said in each case.
-
Implement retry with exponential backoff and jitter, and prove it does not retry
4xx. -
Find an API that supports idempotency keys, read its documentation, and explain in three sentences what problem the key solves.
Extension challenge
-
Speak HTTP by hand over a raw connection with
ncoropenssl s_client. Type the request line, the headers and the blank line yourself. Doing this once makes the protocol permanently concrete. -
Measure the value of a conditional request. Fetch a resource, then re-fetch it with
If-None-Match, and compare the bytes transferred. -
Compare HTTP/1.1 and HTTP/2 on a page with fifty small resources, using
curl --http1.1and--http2, and explain the difference by head-of-line blocking. -
Build a tiny server that returns a different status code per path, then write a client that handles each class correctly.
Quiz
Q1. What are the four parts of an HTTP request, in order?
- Status line, headers, a blank line, then the body
- URL, port, protocol, and payload
- Method, cookie, encryption, body
- Request line, headers, blank line, optional body
Show answer
Answer: D. Request line, headers, blank line, optional body
A request begins with a request line naming the method, path, and HTTP version, followed by headers, a mandatory blank line that marks the end of the headers, and an optional body. A response has the parallel shape but opens with a status line instead of a request line.
Q2. A method is called "idempotent" when:
- Repeating it has the same effect as doing it once
- It is encrypted while on the wire
- It never sends a request body
- It only reads data and never changes anything
Show answer
Answer: A. Repeating it has the same effect as doing it once
Idempotent means repeating the request produces the same end state as sending it once — true of GET, PUT, and DELETE. The property that a method only reads and changes nothing is "safe," which is a different (though related) idea; POST is neither safe nor idempotent.
Q3. Your script POSTs a model prompt, the request times out, and it retries automatically. Why is this riskier for POST than for GET?
- POST is slower than GET, so retries waste more time
- POST is not idempotent, so a retry may create a second resource
- GET cannot be retried at all
- POST responses are always cached, so the retry returns stale data
Show answer
Answer: B. POST is not idempotent, so a retry may create a second resource
GET is idempotent, so repeating it is harmless. POST is not idempotent: if the first request actually completed but the response was lost, the retry can create a duplicate — for a paid model call, that can mean paying twice. This is why retry logic on POST needs care.
Q4. You call a hosted model API and get a 401 status code. What does it mean and what should you do?
- The server crashed; retry the same request in a few seconds
- The resource was not found; check the path
- Authentication failed; retrying unchanged will not help
- You are being rate-limited; slow down your requests
Show answer
Answer: C. Authentication failed; retrying unchanged will not help
401 Unauthorized is a 4xx client error meaning the request lacked valid authentication. It is your request that is wrong, so retrying the identical request forever cannot succeed; you must fix the Authorization header. (429 is rate limiting, 404 is not found, 5xx is a server fault.)
Q5. What distinguishes a 4xx status code from a 5xx status code?
- 4xx codes are encrypted; 5xx codes are not
- 4xx means success; 5xx means redirection
- 4xx is for GET requests; 5xx is for POST requests
- 4xx means the request was wrong; 5xx means the server failed
Show answer
Answer: D. 4xx means the request was wrong; 5xx means the server failed
4xx blames the client — a bad path, bad credentials, or malformed body — so you must fix the request before retrying. 5xx blames the server, so a later retry (ideally with backoff) is a reasonable response. Getting this distinction right is the core of debugging failed API calls.
Q6. Which header carries the credential that decides between a 200 and a 401 for a hosted-model call?
- Authorization
- User-Agent
- Content-Type
- Cache-Control
Show answer
Answer: A. Authorization
The Authorization header carries your credential, most often as "Bearer <token>". If it is missing or invalid the server answers 401; if it is valid the request can proceed. Content-Type describes the body format, User-Agent identifies the client, and Cache-Control governs caching.
Q7. HTTP is described as "stateless." What does that mean, and how do sites keep you logged in anyway?
- The server stores no data at all; login is impossible over HTTP
- Each request is self-contained; identity is re-sent by cookie or token
- The connection is dropped after every byte, so nothing can persist
- State is stored in the URL, which is why URLs are so long
Show answer
Answer: B. Each request is self-contained; identity is re-sent by cookie or token
Statelessness means every request stands alone and the server keeps no memory of you between requests. A session is faked on top: the server sends a Set-Cookie with a session ID, and your client returns it in a Cookie header on every later request, so each self-contained request still lets the server look you up.
Q8. What is the difference between HTTP/1.1, HTTP/2, and HTTP/3?
- They use completely different methods and status codes
- Only HTTP/3 supports POST; the others are read-only
- The wire format differs, but methods and status codes are the same
- HTTP/2 and HTTP/3 remove the need for the Authorization header
Show answer
Answer: C. The wire format differs, but methods and status codes are the same
The versions change transport and efficiency — HTTP/2 uses a compact binary form and multiplexes many requests over one connection, and HTTP/3 swaps in the QUIC transport — but the request/response model, methods, headers, and status codes stay identical. Your tools negotiate the version automatically.
Glossary
- HTTP
- The HyperText Transfer Protocol: the set of rules a client and server follow to exchange request and response messages over a network. It is the protocol every web page load and every hosted-model API call speaks.
- request
- The message a client sends to a server, made of a request line (method, path, version), headers, a blank line, and an optional body.
- response
- The message a server sends back, made of a status line (version, status code, reason), headers, a blank line, and a body.
- method
- The verb of a request that declares intent — GET to read, POST to send data for processing, PUT to replace, PATCH to partially update, DELETE to remove.
- status code
- A three-digit number in the response that summarizes the outcome; its first digit sorts it into a class (1xx informational, 2xx success, 3xx redirection, 4xx client error, 5xx server error).
- header
- A Name: value line carrying metadata about a request or response, such as Content-Type or Authorization; headers come before the blank line that precedes the body.
- body
- The optional payload of a message — the JSON prompt you send in a request, or the HTML or JSON data returned in a response.
- GET
- The method for reading a resource without changing anything; it is both safe (read-only) and idempotent (repeating it has the same effect as doing it once).
- POST
- The method for sending a body to be processed, often creating a resource; it is neither safe nor idempotent, so repeating it may duplicate a side effect. Every hosted-model call is a POST.
- idempotent
- A property of a method meaning that making the same request many times has the same effect as making it once; GET, PUT, and DELETE are idempotent, POST is not.
- stateless
- The property that each HTTP request is self-contained and the server keeps no memory of a client between requests, which is what lets many identical servers share the load.
- Content-Type
- A header declaring the format of the body, such as application/json or text/html, so the receiver parses the bytes correctly.
- Authorization
- A header carrying the credential that proves who the client is, most often as "Bearer <token>"; it is the header that decides between a 200 and a 401.
- cookie
- A small piece of data the server sends with Set-Cookie and the client returns in a Cookie header on later requests, used to fake a continuous session on top of stateless HTTP.
Sources and further reading
- HTTP overview — MDN Web Docs (accessed 2026-07-12)
- HTTP request methods — MDN Web Docs (accessed 2026-07-12)
- HTTP response status codes — MDN Web Docs (accessed 2026-07-12)
- Hypertext Transfer Protocol — Wikipedia (accessed 2026-07-12)
- curl Documentation — curl / Daniel Stenberg (accessed 2026-07-12)
Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.