Skip to content
Index Ai Academy
Phase 8 · HTTP from the wire up

HTTP from the wire up

What really travels between client and server: bytes, headers and bodies.

About 40 minutes · Model names checked November 2026 · Free lesson

What it covers7

First principles

What exactly does an HTTP server read before it sees your JSON?

An HTTP/1.1 request starts with a method and target, then headers. An empty line ends the headers and separates them from any body.

  1. Starting point

    Receive POST /jobs and its headers

  2. What changes

    Find the empty header boundary and determine body length

  3. Result

    Read the body bytes into the request

Compare all three steps
  1. Starting point

    Receive POST /jobs and its headers

  2. What changes

    Find the empty header boundary and determine body length

  3. Result

    Read the body bytes into the request

Complete and reverse the trace

Given Receive POST /jobs and its headers and Read the body bytes into the request, write down the missing step that connects them.

Compare with the worked step

Find the empty header boundary and determine body length

Now take Find the empty header boundary and determine body length and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Receive POST /jobs and its headers. Check that your implementation produces the result shown above.

Try it on a new case

Why can the byte length differ from the character count for a JSON string containing café?

Show worked reasoning

UTF-8 encodes é in two bytes. A Content-Length header describes the transmitted bytes, so it must match the encoded body.

Practice each learning objective
  1. Count the round trips a first API call pays for (DNS, TCP, TLS, HTTP) and what keep-alive saves

    Assume one network round trip each for uncached DNS, TCP, TLS 1.3, and a small HTTP/1.1 request and response. Count the round trips for one request on a new connection and another request reusing that connection.

    Compare your reasoning

    Under those assumptions the first request pays four round trips. Reuse starts with an open, authenticated connection, so the follow-up pays only the request and response. The assumption matters because protocol, cached data, and network conditions can change the first count in a real trace.

  2. Read and write a raw HTTP request and response, byte by byte, and count a body's bytes

    An HTTP/1.1 response body is exactly café encoded in UTF-8. What Content-Length should you send, and which bytes separate the headers from that body?

    Compare your reasoning

    Content-Length is 5, because c, a and f occupy one byte each and é occupies two. End the last header with CRLF and add the empty line as another CRLF. Count only the five body bytes in Content-Length.

  3. Split a URL and encode a query string so no character changes its meaning

    Compose a URL on https://example.test with path /reports and one query field team whose value is North & East. Show how the server can tell the ampersand is data.

    Compare your reasoning

    One valid URL is https://example.test/reports?team=North%20%26%20East. The question mark separates the path and query. Percent encoding keeps the ampersand inside the field so a parser does not treat it as a new query field.

  4. Parse raw HTTP yourself, the first job of every web server, and read the bytes of a model API call

    A request arrives in two chunks. The first contains the request line, all headers, and half the body. Explain what you would parse immediately and what you must delay when reading a fixed-length HTTP body.

    Compare your reasoning

    Parse the request line and headers when the header separator has arrived. Read Content-Length and keep buffering until the stated number of body bytes is available. A network chunk boundary can occur anywhere and cannot tell you that the request is complete.

Try a different case

An import returns HTTP 202 and a Location header. The next request to Location returns a queued status. What has the server actually promised?

Show reasoning for this case

The server accepted the work and supplied a place to check its progress. The status has not promised completion. Handle queued, failed, and complete as separate outcomes.

Run, change, and build

Check this when debugging. Thinking header names are case-sensitive.

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. Why can the byte length differ from the character count for a JSON string containing café?

Why it matters

Every time your code talks to an API, two computers exchange a few lines of plain text. Libraries like requests hide that text, which is convenient until something breaks: a header goes missing, a message is cut short, or a web address is changed on the way. If you can picture the raw messages, you can fix those problems in minutes. It matters for AI work in particular, because a model call is one HTTP request with a long body, and a long reply can spend most of its time waiting on the connection, not on the model.

What you'll be able to do

  • Count the round trips a first API call pays for (DNS, TCP, TLS, HTTP) and what keep-alive saves
  • Read and write a raw HTTP request and response, byte by byte, and count a body's bytes
  • Split a URL and encode a query string so no character changes its meaning
  • Parse raw HTTP yourself, the first job of every web server, and read the bytes of a model API call
Quick check
Your code calls requests.get("https://api.example.com/v1/items"). What travels to the server?
  1. A few lines of text: a request line, headers and a blank line
  2. A compiled program that the server installs
  3. A Python object, sent as it is, which the server runs
  4. Only the URL, with nothing else attached to it
Show the answer

A few lines of text: a request line, headers and a blank line

HTTP is plain text: a line like GET /v1/items HTTP/1.1, then headers such as Host, then a blank line. With https it is encrypted on the way, but it is the same text inside. This lesson builds that text by hand.

The idea: four steps, then some text

This rests on How APIs work, where you sent requests without looking at the bytes.

Picture posting a letter to a company you have never written to. First you look up its address. Then you need a route that gets the letter there. You seal it in an envelope so nobody can read it on the way. Only then does the letter itself matter. A call like requests.get("https://api.gradient.test/v1/campaigns") goes through the same four steps, in order:

  1. DNS turns the name api.gradient.test into a numeric address, the server's IP address.
  2. TCP opens a connection to a numbered door on that address, a port: 443 for HTTPS, 80 for plain HTTP. The internet only tries to deliver small packets, and some get lost. TCP resends them so your program sees a steady stream of bytes in the right order.
  3. TLS encrypts the stream and checks the server's certificate, proof that this really is api.gradient.test. HTTPS is HTTP inside TLS.
  4. HTTP is the letter: a request in a fixed text format, and a reply in the same style.

Each step waits for an answer from the other side, and every wait costs one round trip, the time for a message to go out and a reply to come back. The picture below puts numbers on that.

Quick check
Recall: in requests.post(url, json=data), which part of the call becomes the request's body?
  1. Nothing: json= only sets a header
  2. url, which is sent last
  3. data, written as JSON text
  4. The HTTP method, post
Show the answer

data, written as JSON text

The json= argument is turned into JSON text, and that text is the body. The library also adds Content-Type: application/json and a Content-Length header, as you build by hand below.

Try it now

Keep-alive reuses the open, sealed connection, so the next call pays only the last lane: 25 ms.

A request is text

HTTP/1.1 sends everything as readable text, so it is the best version to learn from. Here is a complete request, exactly as it travels:

POST /v1/campaigns?dry_run=1 HTTP/1.1
Host: api.gradient.test
Content-Type: application/json
Content-Length: 33

{"name": "Spring", "budget": 500}
  • The request line says what you want: the method (POST means "here is something new"), the path with any query after the ?, and the protocol version.
  • The headers are labels on the envelope, one Name: value per line. Names ignore case.
  • A blank line ends the headers.
  • The body, if there is one, is the content of the letter. Content-Length says exactly how many bytes it has, so the server knows where the message stops.

Every line ends with two invisible characters, carriage return and line feed, written \r\n. So the blank line is really \r\n\r\n. The response has the same shape; only its first line differs. It is the status line: the version, a three-digit code and a phrase, such as HTTP/1.1 201 Created. The 200s mean it worked, the 400s mean the request had a problem, and the 500s mean the server did.

In your own words
What does a cold HTTPS call pay for before the server sees a request, and what does keep-alive change?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: build the bytes, then parse them

Building a request means joining text and encoding it, and parsing one means cutting it apart in the same order. Start with building. A byte is the smallest unit a network carries, and .encode() turns text into bytes.

Worked example

Build the bytes yourself

This builds the request above as bytes, the way an HTTP library does before it sends.

import json

body = json.dumps({"name": "Spring", "budget": 500}).encode("utf-8")
head = (
    "POST /v1/campaigns?dry_run=1 HTTP/1.1\r\n"
    "Host: api.gradient.test\r\n"
    "Content-Type: application/json\r\n"
    f"Content-Length: {len(body)}\r\n"
    "\r\n"
)
raw = head.encode("ascii") + body
print(raw)
print(len(body), "body bytes;", len(raw), "bytes in total")
It runs right here in your browser, with nothing to install.

Content-Length counts bytes, not characters. "café" is 4 characters and 5 bytes in UTF-8. Get it wrong and the server waits forever for bytes that never come, or cuts the body short.

Drill

Content-Length counts bytes

Write content_length_header(text): return the header line Content-Length: N, where N is the length of text encoded as UTF-8.

def content_length_header(text):
    return f"Content-Length: {len(text)}"


print(content_length_header('{"name": "Zoë"}'))
In the lesson, your code is checked as you write it.

Now the other direction. A server receives bytes and has to find the request line, the headers and the body. The stepper runs a short parser one line at a time. Watch head, headers and body fill, and watch the header names become lowercase, since names ignore case.

Quick check
What does this print?
raw = b"GET /a?x=1 HTTP/1.1\r\nHost: t\r\n\r\n"
head, sep, rest = raw.partition(b"\r\n\r\n")
print(len(rest), head.split(b"\r\n")[0])
  1. 1 b'GET /a?x=1 HTTP/1.1'
  2. 4 b'GET /a?x=1 HTTP/1.1'
  3. 0 b'GET /a?x=1 HTTP/1.1'
  4. 0 b'Host: t'
Show the answer

0 b'GET /a?x=1 HTTP/1.1'

partition cuts at the blank line. Nothing follows it, so rest is empty and its length is 0. The first line of the head is the request line.

Quick check
A request has Content-Length: 10, but the client sends only 6 body bytes and stops. What does the server do?
  1. It waits for the missing 4 bytes, then usually gives up with a timeout
  2. It guesses the body from the headers
  3. It ignores Content-Length
  4. It reads the 6 bytes and treats them as the whole body
Show the answer

It waits for the missing 4 bytes, then usually gives up with a timeout

Content-Length is how the server knows where the message ends. Too few bytes and it keeps waiting.

Send real requests

The parser reads what arrives; requests writes it. The practice API has an echo route that returns what it received, so you can compare your picture of the bytes with what the server saw. Change the name below to one with an accent and rerun: the query and the JSON body travel differently.

import requests

url = "https://api.gradient.test/v1/echo?q=caf%C3%A9&tag=a&tag=b"
r = requests.post(url, json={"name": "Zoë"})
echo = r.json()
print(r.status_code, echo["method"], echo["path"])
print(echo["query"])
print(echo["json"])
print(echo["headers"].get("content-length"), len('{"name": "Zoë"}'.encode()))

A header you did not set, Content-Length, was added for you, and it is the byte count, not the character count. URLs have a smaller alphabet than text does, so characters with a job in a URL are swapped for a code, percent-encoding: each byte becomes % plus two hex digits. & is 26 in hex, so it travels as %26, and é is two bytes, %C3%A9. Python's urllib.parse gets it right, so never build a query string by hand:

from urllib.parse import urlsplit, urlencode, parse_qs, quote

url = "https://api.gradient.test/v1/products?category=home&q=caf%C3%A9#reviews"
parts = urlsplit(url)
print(parts.scheme, parts.hostname, parts.path, parts.fragment)
print(parse_qs(parts.query))
print(urlencode({"q": "tents & tarps", "max_price": 200}))
print(quote("reports/Q3 final.pdf"))

parse_qs returns lists because a key can repeat: ?tag=a&tag=b is legal and common. The fragment, after the #, never reaches the server; the browser keeps it.

Quick check
What does this print?
from urllib.parse import quote
print(quote("a&b c"))
  1. a&b c
  2. a%26b+c
  3. a%26b%20c
  4. a%2Fb%20c
Show the answer

a%26b%20c

quote turns every byte with a job in a URL into % and two hex digits: & is %26 and a space is %20. (quote_plus and urlencode write a space as + instead.)

Drill

Build a query string safely

Write query_string(params): join name=value pairs with &, in the dictionary's order, escaping each name and value with urllib.parse.quote_plus. Return "" for no parameters.

from urllib.parse import quote_plus


def query_string(params):
    return "&".join(f"{k}={v}" for k, v in params.items())


print(query_string({"q": "R&D budget", "page": 2}))
In the lesson, your code is checked as you write it.
In your own words
How does a server find where the headers end and where the body ends?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML systems: a model call is one request

A call to a model is the same HTTP you just parsed, with a long body. This is the request the Messages API receives:

Where this shows up in an engineer's week

Two things in this lesson matter on the job. The first is time to first byte. A cold call pays the round trips in the picture before the model reads one token, so a service that opens a new connection for every model call is slower than it needs to be. One shared client with keep-alive pays them once; Async HTTP clients builds it. The second is bytes against characters. A prompt with accents or emoji is longer in bytes than in characters, and a proxy with a body limit counts bytes. Both bugs look like "the API is slow" or "the API cuts me off", and both are visible the moment you print the raw request.

Goes deeper in: Build an API server from scratch turns this parser into a server, Transports II: Streamable HTTP sends MCP over the same bytes, and System design fundamentals puts a load balancer in front of the connection.

Quick check
Which of the four steps raises the browser warning that a site's certificate doesn't match its name?
  1. HTTP, which sent the request and read the reply
  2. DNS, which turned the name into an IP address
  3. TCP, which opened the connection to the port
  4. TLS, which checks that the server is who it says it is
Show the answer

TLS, which checks that the server is who it says it is

Checking the certificate is TLS's job. DNS only looks up the address, TCP only carries bytes, and HTTP is the message inside.

In your own words
Why does it help an AI engineer to see the raw bytes of a model call?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 3 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

What does TLS add to an HTTP connection?

  1. Encryption, and proof (a certificate) that the server is who it claims to be
  2. Faster downloads, by compressing each response before it is sent
  3. Automatic retries, so that a dropped connection picks up where it stopped
  4. The ability to send JSON, which plain HTTP can only carry as an attachment

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Part of a free course 127 lessons

Free Python developer course

Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.

Part of a free course 20 lessons

Build and Operate HTTP APIs

Design, test, deploy, and operate an HTTP API that another engineer can use.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write