Skip to content

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.

from fastapi import FastAPI
from 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/42

The browser displays:

Product 42
This page was generated by FastAPI.

That looks simple, but several distinct things happened.


One of the most important distinctions in a FastAPI application is the difference between:

  1. Application startup
  2. 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.

Suppose the server imports the application using the equivalent of:

from main import app

Python now executes the top-level statements in main.py.

from fastapi import FastAPI

FastAPI 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.

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.

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 GET request whose path matches /products/{product_id}, use the product_page function.

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)


You enter:

http://127.0.0.1:8000/products/42

The 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.1
Host: 127.0.0.1:8000
Accept: text/html
User-Agent: Mozilla/5.0

This is not Python. It is an HTTP message.

GET /products/42 HTTP/1.1

This communicates three important facts:

  • GET: the HTTP method
  • /products/42: the requested path
  • HTTP/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.

Host: 127.0.0.1:8000
Accept: text/html
User-Agent: Mozilla/5.0

Headers 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)


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:

  1. Which route matches the HTTP method?
  2. Which route matches the path?

The incoming combination is:

Method: GET
Path: /products/42

FastAPI 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/42

The {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 route function says:

def product_page(product_id: int):

The annotation : int gives FastAPI an instruction:

Extract product_id from the path and convert it into a Python integer before calling this function.

FastAPI converts:

"42"

into:

42

It 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/chair

FastAPI 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.


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:

42

The 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.


The decorator contains:

response_class=HTMLResponse

This 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-8

That 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.


Conceptually, the response resembles:

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 117
<html>
<body>
<h1>Product 42</h1>
<p>This page was generated by FastAPI.</p>
</body>
</html>

The response contains three main parts.

200 OK

This tells the browser that the request succeeded.

Content-Type: text/html; charset=utf-8
Content-Length: 117

The 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 receives the HTTP response and sees:

Content-Type: text/html

It 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

Here is the entire request in compact form:

  1. The server starts and imports main.py.
  2. Python creates the FastAPI application object.
  3. The decorator registers product_page for GET /products/{product_id}.
  4. The application waits.
  5. The browser requests /products/42 using GET.
  6. The server passes that request to FastAPI.
  7. FastAPI finds the matching route.
  8. FastAPI extracts "42" from the URL.
  9. FastAPI validates and converts it into the integer 42.
  10. FastAPI calls product_page(product_id=42).
  11. The function returns an HTML string.
  12. HTMLResponse packages the string into an HTTP response.
  13. The server sends the response to the browser.
  14. The browser parses the HTML and renders the page.

The route is a boundary between the web and your Python code.

On one side:

GET /products/42

On 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.