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.
What really travels between client and server: bytes, headers and bodies.
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.
Receive POST /jobs and its headers
Find the empty header boundary and determine body length
Read the body bytes into the request
Receive POST /jobs and its headers
Find the empty header boundary and determine body length
Read the body bytes into the request
Given Receive POST /jobs and its headers and Read the body bytes into the request, write down the missing step that connects them.
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.
Receive POST /jobs and its headers. Check that your implementation produces the result shown above.
Why can the byte length differ from the character count for a JSON string containing café?
UTF-8 encodes é in two bytes. A Content-Length header describes the transmitted bytes, so it must match the encoded body.
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.
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.
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?
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.
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.
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.
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.
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.
An import returns HTTP 202 and a Location header. The next request to Location returns a queued status. What has the server actually promised?
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.
Check this when debugging. Thinking header names are case-sensitive.
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.
requests.get("https://api.example.com/v1/items"). What travels to the server?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.
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:
api.gradient.test into a numeric address, the server's IP address.api.gradient.test. HTTPS is HTTP inside TLS.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.
requests.post(url, json=data), which part of the call becomes the request's body?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.
Keep-alive reuses the open, sealed connection, so the next call pays only the last lane: 25 ms.
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}
POST means "here is something new"), the path with any query after the ?, and the protocol version.Name: value per line. Names ignore case.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.
Write a sentence or two, then compare it with a good answer in the lesson.
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.
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")
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.
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ë"}'))
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.
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])
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.
Content-Length: 10, but the client sends only 6 body bytes and stops. What does the server do?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.
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.
from urllib.parse import quote print(quote("a&b c"))
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.)
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}))
Write a sentence or two, then compare it with a good answer in the lesson.
A call to a model is the same HTTP you just parsed, with a long body. This is the request the Messages API receives:
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.
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.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
What does TLS add to an HTTP connection?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
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.
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