Follow an HTTP request through FastAPI
Trace one request from the client through TLS, proxy, ASGI server, router, dependencies and handler back to a serialised response.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 13 minutes to read.
In short
An HTTP request is a method, a path, headers and an optional body. Before it reaches your FastAPI function it passes through TLS termination, usually a reverse proxy, and an ASGI server such as Uvicorn, which turns raw bytes into a Python call. FastAPI then routes it, runs dependencies and validation, calls your handler and serialises the return value into a JSON response.
Think of it like this: It is like a parcel through a sorting centre: the security gate opens it (TLS), the front desk (proxy) forwards it, a clerk (ASGI server) logs it into the system, and the right department (route handler) deals with it and sends a reply back the same way.
Explained simply
When a browser or app talks to your API, it sends an HTTP request. Every request has a method, such as GET to read or POST to send data, and a path, such as /v1/questions. It also carries headers, which are small name and value pairs like Content-Type: application/json, and sometimes a body, which holds the actual data.
The request rarely goes straight to your Python code. On the internet it travels over HTTPS, which is HTTP wrapped in TLS encryption. A load balancer or reverse proxy, such as NGINX or a cloud load balancer, usually decrypts it and forwards a plain HTTP request to your app on a private network.
Your app runs inside an ASGI server, most often Uvicorn. The server listens on a port, reads the raw bytes, works out where the headers end and the body starts, and then calls your FastAPI application with a tidy Python description of the request.
FastAPI then finds the route that matches the method and path, checks the input against your type hints, runs any dependencies such as an authentication check, and finally calls your function. Whatever your function returns is turned into JSON and sent back with a status code, like 200 for success.
Knowing these steps helps you debug. A 502 error usually comes from the proxy, a 404 or 405 from the router, a 422 from validation, and a 500 from your own code. Each step leaves different clues.
Press Play on a diagram to walk through it one step at a time.
- 1Client
Sends POST /v1/questions with headers and a JSON body
- 2TLS and proxy
HTTPS is decrypted; the proxy forwards plain HTTP
- 3ASGI server
Uvicorn parses bytes into an ASGI scope and events
- 4Router
FastAPI matches method and path to one route
- 5Dependencies
Validates input, resolves Depends, checks auth
- 6Handler
Your function runs and returns data
- 7Response
Return value is validated, serialised to JSON, sent back
- 502 or 504
- Proxy could not reach the app
- App too slow, proxy timed out
- 404 or 405
- No route matched the path
- Path matched, method did not
- 422
- Body, query or path failed validation
- Handler never ran
- 401 or 403
- Auth dependency rejected the request
- 500
- Unhandled exception in handler
- Return value broke the response model
In depth
The parts of an HTTP request and response
A request starts with a request line: method, path with an optional query string, and protocol version, for example POST /v1/questions?lang=en HTTP/1.1. Headers follow, one per line. Host says which site is wanted, Content-Type says how the body is encoded, Content-Length says how many bytes it has, and Authorization carries credentials such as a bearer token. A blank line separates headers from the body.
The response mirrors this shape: a status line such as HTTP/1.1 201 Created, response headers like Content-Type and Location, then the body. Status codes group by their first digit: 2xx success, 3xx redirect, 4xx the client got something wrong, 5xx the server failed. HTTP/2 and HTTP/3 send the same information in a binary format, but your FastAPI code sees the same method, path, headers and body either way.
- GET reads, POST creates or triggers, PUT replaces, PATCH updates part, DELETE removes
- Query strings are for filters and options, the body for data
- Headers are case-insensitive by name
- A blank line ends the headers in HTTP/1.1
TLS termination and the reverse proxy
In production the client connects with HTTPS. Someone must hold the certificate and decrypt the traffic. Usually that is a managed load balancer or a reverse proxy like NGINX or Caddy, so your app receives plain HTTP from a trusted hop on a private network. This is called TLS termination.
Because the proxy makes the real connection to your app, your app would otherwise think every request came from the proxy over plain HTTP. Proxies fix this with forwarding headers: X-Forwarded-For carries the original client IP and X-Forwarded-Proto the original scheme. Uvicorn reads these headers by default, but only trusts them from addresses listed in --forwarded-allow-ips, which defaults to 127.0.0.1. Set it to your proxy's address, never to everyone on a public port, or any client could fake its IP.
- 1Client
Browser, mobile app or script using HTTPS
- 2Load balancer or reverse proxy
Holds the certificate, decrypts TLS, adds X-Forwarded headers
- 3ASGI server (Uvicorn)
Listens on a port, parses HTTP, manages connections
- 4FastAPI application
Middleware, router, validation, dependencies
- 5Your handler
Business logic that returns data
What the ASGI server does
ASGI is a small contract between servers and frameworks. The server accepts TCP connections, parses HTTP, and for each request calls the application with three things: a scope, a receive function and a send function. The scope is a dictionary with the method, path, query string, headers as byte pairs, client address and scheme. receive returns events with chunks of the body. send takes events that start the response (status and headers) and then deliver the body.
This split is why FastAPI never touches sockets. The server handles keep-alive connections, timeouts, HTTP/1.1 parsing and graceful shutdown. Uvicorn can also run several worker processes, each with its own event loop. Starlette, the toolkit underneath FastAPI, turns the scope and events into the Request object you can use in your code.
- scope: request metadata as a dict
- receive: pulls body chunks in
- send: pushes response start and body out
- Lifespan events also travel over ASGI at startup and shutdown
Inside FastAPI: middleware, routing, dependencies, handler
Middleware wraps the whole application, so it sees every request first and every response last. It is the place for request IDs, timing and CORS. Next the router compares the method and path against each route in the order they were added. No path match gives a 404; a path match with the wrong method gives a 405.
For the matched route, FastAPI reads path, query, header and body parameters and validates them with Pydantic. It also resolves the route's dependencies, which may themselves need other dependencies, and caches each one per request by default. If any value is invalid, FastAPI raises a validation error and answers 422 without calling your function. Only when everything is ready does your handler run with clean, typed arguments.
- Middleware to Router: Pass request on after adding a request ID1Pass request on after adding a request ID
- Router to Dependencies: Route matched: resolve and validate inputs2Route matched: resolve and validate inputs
- Dependencies to Handler: Call handler with typed arguments3Call handler with typed arguments
- Handler to Router: Return a Pydantic model or dict4Return a Pydantic model or dict
- Router to Middleware: Serialised JSON response with status code5Serialised JSON response with status code
How the response is serialised
Your handler usually returns a Pydantic model, a dict or a list. FastAPI checks it against the response model, taken from the return type annotation or the response_model argument. Fields not declared in that model are dropped, which stops internal data such as password hashes leaking by accident. The result is converted to JSON and wrapped in a JSONResponse with Content-Type: application/json.
The status code is 200 unless you set status_code on the route, for example 201 for a create. If you return a Response object yourself, FastAPI sends it as it is and skips this step, which is useful for files and streams. If your return value does not match the response model, FastAPI raises a server error, because that is a bug in your code, not the client's fault.
Learn it in 5 short steps
About 25m each. Track them with a timer in your plan.
- 1Read method, path, headers and body~25m
- 2Place TLS termination and the reverse proxy~25m
- 3Explain what the ASGI server does~25m
- 4Follow routing, dependencies and the handler~25m
- 5See how the response is serialised~25m
Key points
- Method and path pick the route; headers carry metadata such as Content-Type and Authorization; the body carries the data.
- TLS is usually terminated at a load balancer or reverse proxy, so your app sees plain HTTP plus forwarding headers.
- The ASGI server owns sockets and HTTP parsing; FastAPI only sees a scope dictionary and receive and send functions.
- Validation and dependencies run before your handler, so bad input is rejected with a 422 without your code running.
- Your return value is converted to JSON using the response model, which also filters out fields you did not declare.
Key terms
Tap a card to flip it. 0/5 known
Examples
# Watch every part of a request and response
curl -v -X POST http://127.0.0.1:8000/v1/echo \
-H "Content-Type: application/json" \
-d '{"text": "hello"}'
# > lines: method, path, request headers
# < lines: status line and response headers
# last line: the JSON bodyThe -v flag prints the request line, headers and the response status.
See exactly what FastAPI receives
This route returns the parts of the request FastAPI exposes. Run it locally and call it with curl -X POST, adding a header and a JSON body. You will see the method, the path, the header (names arrive in lower case) and the parsed body. If you put a proxy in front, the client host and scheme change, which shows why forwarding headers matter.
from fastapi import FastAPI, Request
app = FastAPI()
@app.post("/v1/inspect")
async def inspect(request: Request) -> dict:
body = await request.json()
return {
"method": request.method,
"path": request.url.path,
"scheme": request.url.scheme,
"client": request.client.host if request.client else None,
"content_type": request.headers.get("content-type"),
"body": body,
}Prove that validation runs before the handler
Add a print call as the first line of a POST route that takes a Pydantic model with a required text field. Send a valid body: the print appears in the server log and you get 200. Send an empty object {} instead: the client receives 422 with a detail list naming the missing field, and nothing is printed. That evidence shows FastAPI rejected the request at the validation step, before your code. Remove the print when you are done.
curl -s -X POST http://127.0.0.1:8000/v1/echo \
-H "Content-Type: application/json" -d '{}'
# {"detail":[{"type":"missing","loc":["body","text"],"msg":"Field required",...}]}Quick reference
- Request = method + path (+ query) + headers + optional body.
- TLS is usually terminated at the load balancer or reverse proxy, not in Uvicorn.
- Uvicorn trusts X-Forwarded-* only from --forwarded-allow-ips (default 127.0.0.1).
- ASGI app = async callable(scope, receive, send).
- Order: middleware, router, validation and dependencies, handler, serialisation.
- 404 no route, 405 wrong method, 422 invalid input, 500 bug in your code.
- The response model filters out any field it does not declare.
- curl -v shows request headers (>) and response headers (<).
Common mistakes
- Trusting the client IP or scheme from forwarding headers sent by anyone; only trust them from your own proxy.
- Doing heavy work in middleware, which runs for every request including health checks.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Run any FastAPI app locally and call one route with curl -v. Label the request line, two request headers, the status line and the response Content-Type.
- Exercise 2medium
Add a GET /v1/whoami route that returns the method, the path, the query parameters and the value of a custom X-Client-Name header, or null if it is missing.
- Exercise 3hard
Write HTTP middleware that times every request and adds an X-Process-Time header in milliseconds. Then call a route that returns 422 and confirm the header is still present.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is FastAPI a web server?
- No. FastAPI is a framework that builds an ASGI application. A server such as Uvicorn runs it and handles the network side.
- Do I need NGINX in front of FastAPI?
- Not for local development. In production something usually terminates TLS and balances load, which can be NGINX, Caddy or a managed cloud load balancer.
- Why do I get 422 instead of 400 for bad input?
- FastAPI uses 422 by default to say the request was well formed HTTP but the data failed validation. You can change this with a custom exception handler, covered in the errors topic.
- What is the difference between ASGI and WSGI?
- WSGI is the older synchronous standard used by Flask and classic Django. ASGI supports async code, long-lived connections and streaming, which FastAPI relies on.