Routing and Request Parameters
8 min read
When building APIs, the fundamental way clients (like a web browser or a mobile app) interact with your server is by sending requests to specific URLs. How your server routes these requests and extracts the data sent by the client dictates how your application functions.
In this guide, we will progressively break down how to handle dynamic paths, URL queries, and JSON data payloads using FastAPI.
🛠️ Setting up the Boilerplate
Before we route anything, we need our server running. FastAPI recently streamlined its installation process for an out-of-the-box, production-ready developer experience [1][3].
Open your terminal and run:
pip install "fastapi[standard]"(Industry Fact: The [standard] flag tells Python to install FastAPI along with standard dependencies like uvicorn, the lightning-fast ASGI web server that actually runs your code, and the new FastAPI CLI [3][4].)
Create a file named main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Server is listening!"}To spin up your development server, run the built-in CLI command:
fastapi dev main.pyThis starts the server on http://127.0.0.1:8000 with auto-reloading enabled, meaning every time you save a file, the server seamlessly refreshes [4].
1. Path Parameters: Creating Dynamic URLs
Definition
A path parameter is a variable segment of a URL path used to identify a specific resource in an API.
The Problem
Imagine you are building a backend for a digital library. You have thousands of books. If you had to hardcode a route for every single book (/books/1, /books/2, /books/3), your codebase would be infinitely long, unmaintainable, and require a redeployment every time a new book is added. You need a way to capture the ID from the URL dynamically.
The Solution
FastAPI allows you to declare dynamic variables directly in the path using curly braces {}. Whatever value the client places in that segment of the URL will be passed into your function as an argument.
from fastapi import FastAPI
app = FastAPI()
@app.get("/books/{book_id}")
def get_book(book_id):
return {"book_id": book_id, "title": "Some Dynamic Book Title"}If a user visits /books/42, the function receives "42" as the book_id.
Progressive Typing
By default, book_id is a string. But in reality, database IDs are often integers. FastAPI leverages Python's standard type hints to automatically validate and convert data.
@app.get("/books/{book_id}")
def get_book(book_id: int):
return {"book_id": book_id, "title": "Some Dynamic Book Title"}Under the hood: FastAPI reads the : int type hint. If a user visits /books/42, FastAPI converts "42" to an integer 42. If the user visits /books/harry-potter, FastAPI automatically intercepts the request and returns a helpful 422 Unprocessable Entity JSON error before your code even runs.
Industry Practice
- Identifiers only: Use path parameters strictly to identify resources (like IDs, usernames, or unique slugs).
- Predefined Choices: Sometimes you only want to accept specific path values. The industry standard is to use Python's
Enumto enforce strict choices.
from enum import Enum
from fastapi import FastAPI
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
app = FastAPI()
@app.get("/models/{model_name}")
def get_model(model_name: ModelName):
# Only "alexnet" or "resnet" are allowed in the URL
return {"model": model_name}2. Query Parameters: Sorting, Filtering, and Pagination
Definition
Query parameters are key-value pairs appended to the end of a URL after a question mark ?, separated by ampersands &. They are used to pass additional information to the server that does not uniquely identify a resource.
The Problem
You have an endpoint /users that returns all users in your system. What if you have 100,000 users? Returning all of them at once will overload your database, spike your server's memory, and crash the client's browser. You need a way to ask the server to only return the first 10 users, or only users who are currently active. Path parameters are wrong for this because we are modifying the behavior of a list, not locating a single entity.
The Solution
In FastAPI, any function parameter that is not declared in the URL path automatically becomes a query parameter.
@app.get("/users")
def get_users(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit, "message": "Returning a slice of users"}If a user visits /users?skip=20&limit=5, the server skips 20 records and returns 5.
Defaults and Optional Parameters
Notice that we gave skip and limit default values (= 0 and = 10). This means if the client just visits /users, the server won't crash; it gracefully falls back to the defaults.
Sometimes, a query parameter should be completely optional, meaning if the client doesn't provide it, its value is None.
from typing import Union
@app.get("/search")
def search_items(query: Union[str, None] = None):
if query:
return {"results": f"Searching for {query}"}
return {"results": "Displaying all items because no query was provided."}(Note: In Python 3.10+, you can write query: str | None = None instead of using Union.)
Industry Practice
- Pagination: Standardizing
skipandlimit(orpageandsize) is universally expected in list endpoints. - Filtering: Use boolean queries like
is_active: bool = Trueto filter data. FastAPI is smart enough to convert?is_active=true,?is_active=1, and?is_active=onall to the Python booleanTrue.
3. Request Body: Receiving JSON Data
Definition
A request body is the data payload sent by a client to a server, typically formatted as JSON, and commonly used in POST, PUT, and PATCH HTTP methods.
The Problem
You want to create a new user account. A user account requires a username, a secure password, a date of birth, and an address. You cannot send this complex, nested data safely through the URL (Path or Query parameters). URLs have length limits and are permanently logged in server logs and browser histories, which is a massive security risk for passwords.
The Solution
You need the client to send the data in the Body of the HTTP request. FastAPI uses Pydantic, a data validation library, to define the exact structure of the data your endpoint expects.
You define a Pydantic BaseModel like a blueprint:
from fastapi import FastAPI
from pydantic import BaseModel
class UserCreate(BaseModel):
username: str
password: str
age: int | None = None # Optional field
app = FastAPI()
@app.post("/users")
def create_user(user: UserCreate):
# 'user' is now a fully validated Python object
return {"message": f"User {user.username} created successfully!"}Under the hood: When a client sends a JSON payload to /users, FastAPI reads the JSON, maps it to your UserCreate Pydantic model, checks if username and password are strings, and checks if age is an integer (if provided). If the client sends {"username": "john", "password": "123", "age": "twenty"}, FastAPI automatically rejects it with a 422 error because "twenty" is not an integer.
Industry Practice
- Model Separation: Never use the same Pydantic model for receiving data and returning data. For example, your
UserCreatemodel requires a password, but yourUserResponsemodel should absolutely not include the password field. - Data Validation: Pydantic is powerful. Industry standards involve using it to validate string lengths, email formats, and number ranges (e.g., age must be
> 0).
4. Combining Path, Query, and Body Parameters Effectively
Definition
Combining parameters refers to the concurrent use of path parameters, query parameters, and a request body in a single API endpoint request.
The Problem
Real-world enterprise systems are rarely simple. Imagine managing an e-commerce inventory. A warehouse manager needs to update the stock count of a specific product. However, they also need to pass a temporary flag indicating whether to notify the marketing team about the restock.
You need:
- A way to target the exact product (Path).
- The updated stock data (Body).
- A flag to trigger notifications (Query).
The Solution
FastAPI handles the combination of all three seamlessly. You just declare them all in your function signature. FastAPI's engine is smart enough to categorize them based on these rules:
- If the parameter is declared in the path
"/products/{product_id}", it is a Path Parameter. - If the parameter is a Pydantic
BaseModel, it is a Request Body. - If the parameter is a singular type (like
int,str,bool) and is not in the path, it is a Query Parameter.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# 1. The Body blueprint
class StockUpdate(BaseModel):
new_quantity: int
restocked_by: str
# 2. The Endpoint
@app.put("/products/{product_id}")
def update_product_stock(
product_id: int, # Path Parameter
stock_data: StockUpdate, # Request Body
notify_marketing: bool = False # Query Parameter
):
# Simulation of database logic
response = {
"product_id": product_id,
"updated_quantity": stock_data.new_quantity,
"manager": stock_data.restocked_by,
"marketing_notified": notify_marketing
}
return responseIf the manager sends a PUT request to /products/1042?notify_marketing=true with the JSON body {"new_quantity": 500, "restocked_by": "Alice"}, FastAPI flawlessly maps all three sources of data into the respective variables.
Industry Practice
- Order Matters: In Python, parameters with default values (like
notify_marketing: bool = False) must come after parameters without default values (likeproduct_idandstock_data). - Keep URLs Clean: Do not overload query parameters if the data logically belongs to the entity being updated. If
notify_marketingwas a permanent setting on the product rather than a one-time trigger, it should be moved inside theStockUpdatebody model.
📚 References & Extra Reading
Challenge
You are building an API for a warehouse inventory management system. Your task is to create a single PUT endpoint to update an existing item's information.
This endpoint must combine path parameters, query parameters, and a request body.
Endpoint Requirements:
- Method:
PUT - Path:
/inventory/{item_id} - Path Parameter:
item_id: Must be validated as aUUID.
- Request Body:
- The endpoint must expect a JSON request body conforming to a Pydantic model named
ItemUpdate. - The
ItemUpdatemodel must contain the following fields:name: astr.quantity: anintthat must be greater than zero.supplier: a nested JSON object.
- The nested
supplierobject must conform to a separate Pydantic model namedSupplierInfo. - The
SupplierInfomodel must contain:supplier_name: astr.contact_email: a valid email string.
- The endpoint must expect a JSON request body conforming to a Pydantic model named
- Query Parameters:
force_update: an optionalboolthat defaults toFalse.updated_by: an optionalstrto log the user performing the update. If not provided, it should beNone.
- Return Value:
- The endpoint function should return a dictionary containing the
item_id, all the data received from theItemUpdaterequest body, and the values of theforce_updateandupdated_byquery parameters.
- The endpoint function should return a dictionary containing the
Expected result
Your final code should consist of a complete FastAPI application with two Pydantic models and one endpoint function.
- A Pydantic
BaseModelnamedSupplierInfowith two fields:supplier_name(str) andcontact_email(EmailStr). - A second Pydantic
BaseModelnamedItemUpdatewith three fields:name(str),quantity(int), andsupplier(typed asSupplierInfo). Thequantityfield should useField(gt=0)for validation. - A
PUTendpoint function decorated with@app.put("/inventory/{item_id}"). - The function signature should look similar to this, correctly typing all parameters:
async def update_item(item_id: UUID, item: ItemUpdate, force_update: bool = False, updated_by: Optional[str] = None):. - The function body should return a dictionary that combines all the input data, for example:
{"item_id": item_id, "update_data": item, "force_update": force_update, "updated_by": updated_by}.