Chapter 3 · HTTP and Web APIs
How the Web Works: Clients, Servers and HTTP
- Page 11 of 22
- 17 min read
Every time your Python code "calls an LLM", it sends a few hundred bytes of text over a network connection to someone else's computer and reads the text that comes back. That text follows a set of rules called HTTP. The OpenAI and Anthropic SDKs, a chatbot's web page talking to its backend, a model server answering predictions, a webhook from GitHub: all of them are HTTP requests and responses underneath.
When something goes wrong (a 401, a timeout, a 429 "too many requests", a response that is not JSON), the people who fix it quickly are the ones who can picture that conversation. This page builds that picture: who talks to whom, what an HTTP message really looks like, how a URL is put together, how a name like api.openai.com becomes a computer, what HTTPS adds, and how to watch real requests with curl -v and your browser's DevTools.
What you will learn
- The difference between the internet and the web, and what a client and a server are.
- What an HTTP request and response look like as plain text, line by line.
- The parts of a URL, and how to take one apart and build one safely in Python.
- What DNS and HTTPS/TLS do for you, in a few sentences each.
- How to watch HTTP traffic with
curl -vand the browser's Network tab.
The internet, the web, clients and servers
The internet is the network: millions of computers connected so that any one can send data to any other, using the IP and TCP protocols. The web is one thing that runs on top of it: documents and data addressed by URLs and fetched with HTTP. Email, video calls and online games also use the internet, but not (mostly) HTTP.
On the web, every conversation has two sides:
- A client starts the conversation by sending a request. Your browser is a client. So is
curl, a Python script usingrequests, a mobile app, and the OpenAI SDK inside your notebook. - A server is a program that waits for requests and answers each one with a response. It runs on a machine somewhere: a data centre, a cloud container, or your own laptop.
| Situation | Client | Server |
|---|---|---|
| You open a web page | Browser | The site's web server |
| Your notebook asks an LLM a question | The openai or anthropic SDK in Python | The provider's API servers |
| A chat app shows the answer | JavaScript in the chat page | Your backend (FastAPI, later in this tutorial) |
| Your backend asks for the weather | Your backend (now acting as a client) | A weather API |
The last row matters: "client" and "server" are roles in one conversation, not kinds of machines. A typical AI backend is a server to its users and a client to the LLM provider, the database and other APIs at the same time.
A server to practise on
To see real traffic you need a server. This tutorial uses the BitByte Practice API, a small web API that runs on your own computer, needs no internet and returns the same answers on every machine, so your output matches the page. You set it up properly on the page Web APIs and REST: Reading Docs and Testing with curl. If you want to run this page's commands now, jump to the section "Setting up the Practice API" there, do its two steps (save the file, start it with fastapi run practice_api.py --port 8800 in a second terminal), and come back. You can also just read along: every output below is real.
Ask it something with curl, a command-line HTTP client that ships with macOS, Linux and Windows 10/11:
curl -s http://localhost:8800/{"name":"BitByte Practice API","version":"1.0.0","docs":"/docs"}-s (silent) hides curl's progress meter, which otherwise appears when curl's output goes into a pipe or a file; this tutorial uses it almost everywhere. localhost means "this same computer", and 8800 is the port the server listens on. Your terminal (the client) sent a request, the server answered, and curl printed the body of the answer. That body is JSON, the format almost every API uses.
What HTTP looks like
HTTP is a text protocol: a request and a response are lines of text with a fixed shape. Here is the shape, as a picture:
REQUEST (client → server) RESPONSE (server → client)
GET /v1/courses/2 HTTP/1.1 ← request line HTTP/1.1 200 OK ← status line
Host: localhost:8800 ← headers content-type: application/json ← headers
User-Agent: curl/8.5.0 content-length: 75
Accept: */*
← blank line ← blank line
(body: empty for GET) ← body {"id":2,"title":"Python for AI",...} ← body- The request line says what the client wants: a method (
GET= "give me"), a path (/v1/courses/2) and the protocol version. - The status line says how it went: a three-digit status code (
200) and a short reason (OK). - Headers are
Name: valuelines with extra information: which host, what format the body is in, how long it is, who is asking, and (later) your API key. - A blank line ends the headers. Everything after it is the body.
Proving it: HTTP by hand
You do not need a special library to speak HTTP. Python's socket module opens a plain network connection; we type the request ourselves and print exactly what comes back. (One header, date, changes every second, so we leave it out of the printout.)
import socket
request = (
"GET /v1/courses/2 HTTP/1.1\r\n"
"Host: localhost:8800\r\n"
"Connection: close\r\n"
"\r\n"
)
with socket.create_connection(("localhost", 8800)) as sock:
sock.sendall(request.encode("ascii"))
raw = b""
while chunk := sock.recv(4096):
raw += chunk
for line in raw.decode("utf-8").split("\r\n"):
if not line.lower().startswith("date:"):
print(line)HTTP/1.1 200 OK
server: uvicorn
content-length: 75
content-type: application/json
connection: close
{"id":2,"title":"Python for AI","level":"beginner","hours":12,"rating":4.8}What to notice:
- Lines end with
\r\n(carriage return + line feed), and an empty line ends the headers. That is the whole "format". Hostis required in HTTP/1.1, because one server machine often hosts many sites.Connection: closeasked the server to hang up after answering, so our loop knows when to stop reading. Normal clients keep the connection open and reuse it (you will use that withrequests.Sessionlater).content-length: 75is the size of the body in bytes. Count the JSON characters: 75.- Header names are case-insensitive: the server wrote
content-type, documentation often writesContent-Type. Both mean the same.
You will never write HTTP by hand in real work; curl, requests and SDKs do it. But now you know there is no magic: an LLM API call is this, with a POST, a JSON body and an Authorization header.
HTTP versions
The text above is HTTP/1.1. Newer versions change how the bytes travel, not what they mean:
| Version | On the wire | What you need to know |
|---|---|---|
| HTTP/1.1 | Plain text over TCP | Still everywhere; easy to read in curl -v. |
| HTTP/2 | Binary frames, many requests share one connection | Used by most big APIs and browsers. Same methods, headers, status codes. |
| HTTP/3 | Binary frames over QUIC (UDP) | Faster on bad mobile networks. Same meaning again. |
Methods, paths, headers, status codes and bodies work the same in all three, which is why this tutorial can teach with HTTP/1.1.
One more property: HTTP is stateless. Each request stands alone; the server does not remember your previous request unless you send something that identifies you (a token, a cookie). This is why every LLM API call sends the API key again, and why a chat API needs the whole conversation history in each request: the server keeps no memory between calls.
URLs and their parts
A URL (Uniform Resource Locator) says where something is and how to get it. Take this one apart:
https://api.example.com:8443/v1/courses?level=beginner&page=2#reviews
└─┬─┘ └──────┬──────┘ └┬─┘└────┬────┘ └─────────┬─────────┘ └──┬──┘
scheme host port path query fragment| Part | Example | Meaning |
|---|---|---|
| Scheme | https | Which protocol: http or https. |
| Host | api.example.com | Which machine (a domain name or an IP address). |
| Port | 8443 | Which program on that machine. Usually left out: http means 80, https means 443. |
| Path | /v1/courses | Which resource on the server. |
| Query string | level=beginner&page=2 | Extra options as key=value pairs joined by &, after a ?. |
| Fragment | reviews | A place inside the page, after #. Used by the browser only; never sent to the server. |
Python's standard library can split a URL for you, which is safer than slicing strings:
from urllib.parse import urlsplit, parse_qs
url = "https://api.example.com:8443/v1/courses?level=beginner&page=2#reviews"
parts = urlsplit(url)
print("scheme: ", parts.scheme)
print("host: ", parts.hostname)
print("port: ", parts.port)
print("path: ", parts.path)
print("query: ", parts.query)
print("fragment:", parts.fragment)
print(parse_qs(parts.query))scheme: https
host: api.example.com
port: 8443
path: /v1/courses
query: level=beginner&page=2
fragment: reviews
{'level': ['beginner'], 'page': ['2']}parse_qs gives lists because a key may repeat (?tag=ai&tag=python). Also note that query values are always text: '2', not 2. The server decides whether to treat it as a number.
Special characters: percent-encoding
A URL may only contain a limited set of characters. Spaces, ?, &, #, quotes and non-English letters inside a value must be percent-encoded: each byte becomes % plus two hex digits. Never glue such values into a URL by hand; let a library encode them:
from urllib.parse import urlencode, quote
print(urlencode({"q": "what is RAG?", "city": "Cox's Bazar"}))
print(quote("ঢাকা"))q=what+is+RAG%3F&city=Cox%27s+Bazar
%E0%A6%A2%E0%A6%BE%E0%A6%95%E0%A6%BEThe ? inside the question became %3F; otherwise the server would think a new query string starts there. A space is + in a query string (or %20). The Bangla word "ঢাকা" is 12 bytes in UTF-8, so it becomes 12 %XX groups. requests and curl --data-urlencode do this for you, as you will see on the next pages.
DNS: from a name to an address
Computers connect to IP addresses such as 127.0.0.1 (IPv4) or ::1 (IPv6), not to names. DNS (the Domain Name System) is the internet's phone book: before connecting to api.openai.com, your computer asks a DNS resolver (usually run by your ISP, your router or a public service) "what is the address for this name?", caches the answer for a while, and then connects to that address. localhost is special: it is answered from your own machine and always means "this computer".
import socket
print(socket.gethostbyname("localhost"))127.0.0.1When DNS fails you see errors like Name or service not known or getaddrinfo failed (Windows) before any HTTP happens. That usually means a typo in the host name, no internet, or a company network that blocks the name, not a problem with the API itself.
HTTPS and TLS
Plain HTTP travels as readable text, so anyone on the path (the café Wi-Fi, a compromised router) could read or change it, including your API key. HTTPS is HTTP sent inside a TLS connection (TLS 1.3 today). TLS gives you three things:
| Guarantee | What it means | Why it matters for AI apps |
|---|---|---|
| Encryption | Only the two ends can read the traffic. | Prompts, user data and API keys stay private on the way. |
| Integrity | Any change on the way is detected. | Nobody can quietly alter a model's answer or your request. |
| Server identity | The server proves who it is with a certificate signed by a certificate authority your system trusts. | You really are talking to api.anthropic.com, not an impostor. |
The HTTP messages inside are exactly the same as before; TLS just wraps them. Two practical rules follow:
- Use
https://for everything that leaves your computer. Every real AI provider only accepts HTTPS. Plainhttp://is fine only forlocalhost, as with the Practice API, because the traffic never leaves your machine. - Never turn off certificate checks (
curl -k,verify=Falseinrequests) to "make an error go away". A certificate error means either a broken setup (fix it) or someone in the middle (stop).
With curl -v https://…, the lines starting with * show the TLS handshake: the TLS version, the server certificate's subject (the name it was issued to), its expiry date and whether verification succeeded. Read them when an HTTPS call fails before any status code appears.
Watching traffic with curl -v
-v (verbose) makes curl show the conversation: lines starting with > are what curl sent, lines starting with < are what the server sent back, and lines starting with * are curl's own notes (looking up the name, connecting, TLS). curl writes those to stderr, so 2>&1 joins them with the body. To keep this page's output stable, we keep only the > and < lines and drop the changing date header (tr -d '\r' removes the invisible carriage returns):
curl -sv http://localhost:8800/v1/courses/2 2>&1 | grep -E '^[<>]' | grep -v '^< date' | tr -d '\r'> GET /v1/courses/2 HTTP/1.1
> Host: localhost:8800
> User-Agent: curl/8.5.0
> Accept: */*
>
< HTTP/1.1 200 OK
< server: uvicorn
< content-length: 75
< content-type: application/json
<It is the same request and response you wrote by hand above. curl added two headers on its own: User-Agent (who is asking; your curl version number may differ) and Accept: */* ("any format is fine"). When you run plain curl -v yourself, without the filters, you will also see the * lines and the body.
If you only want the response's status line and headers together with the body, -i (include) is shorter:
curl -si "http://localhost:8800/v1/weather?city=Dhaka" | grep -v '^date' | tr -d '\r'HTTP/1.1 200 OK
server: uvicorn
content-length: 64
content-type: application/json
{"city":"Dhaka","temp_c":31.5,"humidity":78,"condition":"Humid"}The URL is in double quotes. That is not decoration: in bash, ? is a wildcard and & runs a command in the background, so an unquoted URL with a query string can break in confusing ways.
Ask for a city the server does not know, and the status line tells you before you read the body:
curl -si "http://localhost:8800/v1/weather?city=Comilla" | grep -v '^date' | tr -d '\r'HTTP/1.1 404 Not Found
server: uvicorn
content-length: 42
content-type: application/json
{"detail":"No weather data for 'Comilla'"}404 means "not found". The next page goes through status codes properly.
Watching traffic in the browser: DevTools
Every browser has the same tool built in. Open http://localhost:8800/v1/courses (or any website), then press F12 (macOS: Cmd+Option+I) and choose the Network tab. Reload the page. Each row is one HTTP request:
| Column / panel | What it shows |
|---|---|
| Name, Method, Status | The path, GET/POST…, and the status code (red for 4xx/5xx). |
| Type, Size, Time | The content type, how many bytes, and how long it took. |
| Headers (click a row) | The full request and response headers, like curl -v. |
| Payload / Preview / Response | The request body, and the response body (pretty or raw). |
| Timing | DNS lookup, connecting, TLS, waiting for the server, downloading. |
Two tricks used daily: tick Preserve log so requests survive a page change, and right-click a request → Copy → Copy as cURL to get a curl command that repeats exactly that request in your terminal. Open a chat app (ChatGPT, Claude, your own later) with the Network tab open and send a message: you will see the POST that carries your prompt, and an answer that arrives bit by bit as a stream (the EventStream view). That is the same HTTP you are learning here.
"Copy as cURL" includes your cookies and tokens. Treat the copied command like a password: do not paste it into a chat, an issue or a commit.
Where you will use this
- Debugging LLM calls. When an SDK raises an error, the useful facts are HTTP facts: which URL, which status code, which headers (rate-limit, retry-after) and which body. Many SDKs can log the raw requests for this reason.
- Backends calling backends. Your FastAPI service will be a server for its users and a client for model providers, vector databases and other APIs. Each hop is a request/response like the one above.
- Front-end and back-end bugs. The Network tab answers "did the browser even send the request, and what did the server say?" in seconds, before anyone opens the code.
- Security reviews. "Is anything sent over plain
http://? Are keys in URLs (which end up in logs) instead of headers?" are questions about URLs and headers.
Common mistakes
- Unquoted URLs in the terminal.
curl http://localhost:8800/v1/courses?level=beginner&page=2runscurl …?level=beginnerin the background and then a separate "command"page=2. Always put URLs with?or&in quotes. - Building URLs by string concatenation.
"...?q=" + questionbreaks as soon as the question contains?,&,#or a Bangla letter. Useurlencode,params=inrequests, orcurl --data-urlencode. - Thinking the fragment reaches the server. Anything after
#stays in the browser. If the server needs a value, put it in the path or the query. - Using
http://or turning off certificate checks for real services. Your API key then travels readable, or you might be talking to an impostor. Usehttps://, and fix certificate errors instead of hiding them. - Confusing "can't connect" with an HTTP error. "Connection refused" or "Name or service not known" means no HTTP conversation happened at all (server not running, wrong port, wrong host). A 404 or 500 means the server did answer. The fix is different.
Try it yourself
- Easy: With curl, get
/healthfrom the Practice API, then the weather for Sylhet. Show the status line and headers for the Sylhet request too. - Medium: In Python, split
http://localhost:8800/v1/courses?level=advanced&per_page=2into its parts withurlsplitand print the host, the port, the path and the query as a dictionary. Which port would be used if the URL werehttps://api.example.com/v1/courses? - Hard: Change the raw-socket program so it asks for
/v1/courses/99and prints only the status line and the body. Then explain how the program finds where the body starts.
Answers
# 1
curl -s http://localhost:8800/health
echo
curl -si "http://localhost:8800/v1/weather?city=Sylhet" | grep -v '^date' | tr -d '\r'{"status":"ok"}
HTTP/1.1 200 OK
server: uvicorn
content-length: 64
content-type: application/json
{"city":"Sylhet","temp_c":27.4,"humidity":85,"condition":"Rain"}The echo prints a line break, because the first response body does not end with one.
# 2
from urllib.parse import urlsplit, parse_qs
parts = urlsplit("http://localhost:8800/v1/courses?level=advanced&per_page=2")
print(parts.hostname, parts.port, parts.path)
print(parse_qs(parts.query))
print(urlsplit("https://api.example.com/v1/courses").port)localhost 8800 /v1/courses
{'level': ['advanced'], 'per_page': ['2']}
Noneport is None when the URL does not say it. The client then uses the scheme's default: 443 for https.
# 3
import socket
request = (
"GET /v1/courses/99 HTTP/1.1\r\n"
"Host: localhost:8800\r\n"
"Connection: close\r\n"
"\r\n"
)
with socket.create_connection(("localhost", 8800)) as sock:
sock.sendall(request.encode("ascii"))
raw = b""
while chunk := sock.recv(4096):
raw += chunk
head, body = raw.decode("utf-8").split("\r\n\r\n", 1)
print(head.split("\r\n")[0])
print(body)HTTP/1.1 404 Not Found
{"detail":"Course 99 not found"}The headers end at the first empty line, which in the raw bytes is \r\n\r\n (the end of the last header line plus an empty line). Splitting once at that marker gives the head (status line + headers) and the body. Real clients also read content-length to know how many body bytes to expect.
Summary
- The internet connects computers; the web is URLs plus HTTP on top. A client sends a request, a server sends a response. One program can be both.
- An HTTP message is a start line (request line or status line), headers, a blank line and an optional body. HTTP/2 and HTTP/3 change the transport, not the meaning. HTTP is stateless.
- A URL has a scheme, host, port, path, query string and fragment. Let libraries split and encode URLs; never glue user text into them.
- DNS turns names into IP addresses. HTTPS = HTTP inside TLS: encrypted, tamper-proof, and the server proves its identity. Use it for everything beyond
localhost. curl -v,curl -iand the browser's Network tab let you see the real requests and responses. Look there first when an API call fails.
Next: HTTP Methods, Status Codes, Headers and JSON. You have seen GET and 200/404; next come the other methods, the full family of status codes, the headers APIs care about, and JSON bodies.

