01 · From Browser to Route and Back
Today we’ll isolate the first section of the complete lifecycle:
Browser → HTTP request → FastAPI application → router → Python function → HTTP response → browser
We are deliberately leaving middleware, authentication, dependencies, services, and databases out for now. Before adding those layers, you need a precise mental picture of the basic round trip.
The application
Section titled “The application”from fastapi import FastAPIfrom fastapi.responses import HTMLResponse
app = FastAPI()
@app.get("/products/{product_id}", response_class=HTMLResponse)def product_page(product_id: int): return f""" <html> <body> <h1>Product {product_id}</h1> <p>This page was generated by FastAPI.</p> </body> </html> """Imagine this code is saved in main.py and the application is running locally.
You enter this URL in the browser:
http://127.0.0.1:8000/products/42The browser displays:
Product 42
This page was generated by FastAPI.
That looks simple, but several distinct things happened.
Two different phases
Section titled “Two different phases”One of the most important distinctions in a FastAPI application is the difference between:
- Application startup
- Request handling
Python does not reread the entire file from the beginning every time someone visits a page.
Instead, Python imports and executes main.py when a server worker loads the application. That builds the application and registers its routes. Multiple workers or a development reload can each perform that setup; ordinary requests reuse the resulting application in their worker.
Later, each HTTP request uses the application that has already been constructed.
Phase 1: The application starts
Section titled “Phase 1: The application starts”Suppose the server imports the application using the equivalent of:
from main import appPython now executes the top-level statements in main.py.
Importing FastAPI
Section titled “Importing FastAPI”from fastapi import FastAPIFastAPI is a Python class supplied by the FastAPI package.
At this moment, we have imported the blueprint for creating a FastAPI application. We have not created the actual application yet.
This is the same distinction as:
class Car: ...versus:
my_car = Car()Car is the class. my_car is a particular object created from that class.
Creating the application object
Section titled “Creating the application object”app = FastAPI()Here, Python calls the FastAPI class and creates an instance.
The variable app points to that instance.
This object will eventually contain:
- Route registrations
- Middleware
- Exception handlers
- Application configuration
- Startup and shutdown behavior
- OpenAPI documentation information
The web server needs this app object because it is the callable ASGI application to which incoming requests will be passed.
A useful distinction:
- The server process listens for network traffic.
- The FastAPI application decides what to do with the requests it receives.
FastAPI itself is not simply “watching port 8000.” The server handles the lower-level connection and passes an organized representation of each request into the FastAPI application.
Registering the route
Section titled “Registering the route”Python then reaches this code:
@app.get("/products/{product_id}", response_class=HTMLResponse)def product_page(product_id: int): ...The decorator is executed when main.py is imported.
It tells the app object:
When you receive a
GETrequest whose path matches/products/{product_id}, use theproduct_pagefunction.
FastAPI therefore adds an entry to its internal routing table. Conceptually, that entry resembles:
| HTTP method | Path pattern | Handler |
|---|---|---|
GET |
/products/{product_id} |
product_page |
The exact internal representation is more sophisticated, but this is the correct mental model.
The important point is that the decorator registers the function during startup. It does not handle an HTTP request at that moment.
The function underneath is defined:
def product_page(product_id: int):But its body does not run yet.
The application is now assembled and waiting for traffic. FastAPI’s own documentation describes @app.get(...) as the path-operation decorator connecting an HTTP method and path to the function below it. (FastAPI documentation)
Phase 2: The browser makes a request
Section titled “Phase 2: The browser makes a request”You enter:
http://127.0.0.1:8000/products/42The browser interprets the URL in pieces:
| Part | Meaning |
|---|---|
http |
Communication protocol |
127.0.0.1 |
Host |
8000 |
Port |
/products/42 |
Path |
127.0.0.1 means the computer on which the browser itself is running.
Port 8000 identifies the particular server process that should receive the connection.
The browser creates an HTTP request conceptually resembling:
GET /products/42 HTTP/1.1Host: 127.0.0.1:8000Accept: text/htmlUser-Agent: Mozilla/5.0This is not Python. It is an HTTP message.
The request line
Section titled “The request line”GET /products/42 HTTP/1.1This communicates three important facts:
GET: the HTTP method/products/42: the requested pathHTTP/1.1: the protocol version represented here
GET conventionally means:
Give me a representation of this resource without changing it.
The browser is asking for the resource identified by /products/42.
The headers
Section titled “The headers”Host: 127.0.0.1:8000Accept: text/htmlUser-Agent: Mozilla/5.0Headers are additional metadata.
Host identifies the destination website. This becomes especially important when one server hosts multiple domains.
Accept tells the server which response formats the browser understands or prefers.
User-Agent provides information about the client making the request.
A normal GET request usually does not need a request body. A POST request submitting a form or JSON data often does.
HTTP follows a client-server model: the browser initiates a request, and the server returns a response. The browser then interprets that response. (MDN HTTP overview)
FastAPI receives the request
Section titled “FastAPI receives the request”The server accepts the network traffic, interprets it through the ASGI protocol, and passes it to the FastAPI application.
FastAPI now needs to answer two questions:
- Which route matches the HTTP method?
- Which route matches the path?
The incoming combination is:
Method: GETPath: /products/42FastAPI examines its routing table and finds:
@app.get("/products/{product_id}")The method matches because both specify GET.
The path also matches:
Pattern: /products/{product_id}Actual: /products/42The {product_id} portion is a path parameter. It means that this segment may contain a value that FastAPI should extract.
FastAPI initially receives that value from the URL as text:
"42"URLs are text. The browser does not send a native Python integer across the internet.
The type annotation becomes active
Section titled “The type annotation becomes active”The route function says:
def product_page(product_id: int):The annotation : int gives FastAPI an instruction:
Extract
product_idfrom the path and convert it into a Python integer before calling this function.
FastAPI converts:
"42"into:
42It then effectively makes this function call:
product_page(product_id=42)That is not literally the source code FastAPI generates, but it accurately describes the result.
Inside the function, product_id is now a normal Python integer.
If the browser requested:
/products/chairFastAPI could not convert "chair" into an integer.
In that case, it would not call product_page() with invalid data. It would generate a validation error response.
This is an early glimpse of a major FastAPI principle:
Function signatures are not merely documentation. FastAPI reads them as instructions.
Later, the same idea will power query parameters, Pydantic request bodies, dependencies, authentication, and database sessions.
The route function runs
Section titled “The route function runs”Now Python executes:
return f"""<html> <body> <h1>Product {product_id}</h1> <p>This page was generated by FastAPI.</p> </body></html>"""The f before the string makes this an f-string.
Python replaces:
{product_id}with:
42The function therefore returns a Python string containing:
<html> <body> <h1>Product 42</h1> <p>This page was generated by FastAPI.</p> </body></html>Notice where responsibility changes:
- FastAPI selected and prepared the function call.
- Your Python function decided what content to return.
- FastAPI will turn that Python result into an HTTP response.
The function does not communicate directly with Chrome or Safari. It returns a Python value to the framework.
Why response_class=HTMLResponse matters
Section titled “Why response_class=HTMLResponse matters”The decorator contains:
response_class=HTMLResponseThis tells FastAPI that the returned content should be presented as HTML.
Without it, FastAPI’s normal default is to treat ordinary returned values as JSON-compatible response content.
HTMLResponse causes the response to include a content-type header resembling:
Content-Type: text/html; charset=utf-8That header tells the browser:
Interpret this response body as HTML.
The browser does not know or care that the response originated as a Python f-string. By the time it reaches the browser, it is an HTTP response containing text and metadata.
FastAPI builds the HTTP response
Section titled “FastAPI builds the HTTP response”Conceptually, the response resembles:
HTTP/1.1 200 OKContent-Type: text/html; charset=utf-8Content-Length: 117
<html> <body> <h1>Product 42</h1> <p>This page was generated by FastAPI.</p> </body></html>The response contains three main parts.
Status
Section titled “Status”200 OKThis tells the browser that the request succeeded.
Headers
Section titled “Headers”Content-Type: text/html; charset=utf-8Content-Length: 117The headers describe the response.
Content-Type explains how to interpret the body.
Content-Length communicates the body’s exact size in bytes when that header is present. The server normally calculates it; you do not manually write it. Streaming responses may send their body without a Content-Length header.
<html> ...</html>This is the actual content the browser requested.
The browser renders the result
Section titled “The browser renders the result”The browser receives the HTTP response and sees:
Content-Type: text/htmlIt therefore parses the response body as HTML.
It constructs its internal document representation and renders:
<h1>as a large heading<p>as a paragraph
The browser never sees:
def product_page(product_id: int):It does not receive your Python source code.
It receives only the output produced by that code.
Likewise, FastAPI does not “display the page.” FastAPI produces an HTTP response. The browser displays the page.
That separation is fundamental:
| Component | Responsibility |
|---|---|
| Browser | Creates the request and renders the response |
| HTTP | Defines the request-response message format |
| Server | Accepts network traffic and communicates with the ASGI app |
| FastAPI | Matches the route, prepares arguments, and builds the response |
| Route function | Executes your application-specific Python logic |
The complete execution trace
Section titled “The complete execution trace”Here is the entire request in compact form:
- The server starts and imports
main.py. - Python creates the
FastAPIapplication object. - The decorator registers
product_pageforGET /products/{product_id}. - The application waits.
- The browser requests
/products/42usingGET. - The server passes that request to FastAPI.
- FastAPI finds the matching route.
- FastAPI extracts
"42"from the URL. - FastAPI validates and converts it into the integer
42. - FastAPI calls
product_page(product_id=42). - The function returns an HTML string.
HTMLResponsepackages the string into an HTTP response.- The server sends the response to the browser.
- The browser parses the HTML and renders the page.
The key mental model
Section titled “The key mental model”The route is a boundary between the web and your Python code.
On one side:
GET /products/42On the other:
product_page(product_id=42)FastAPI performs the translation.
That is its central job: turn HTTP input into a valid Python function call, then turn the function’s result back into an HTTP response.
In the next tutorial, middleware can be inserted around this process. Instead of the request going directly to the router, middleware gets an opportunity to inspect or modify the request before routing—and to inspect or modify the response on its way back out.