How to Use Multiple Path Parameters in FastAPI
In FastAPI, you can use multiple path parameters by defining them in the route path inside
{} brackets, separated by slashes. Each parameter is then declared as a function argument with its type, allowing FastAPI to extract and pass them to your function automatically.Syntax
To use multiple path parameters in FastAPI, include each parameter inside curly braces {} in the route path. Then, add matching function parameters with type annotations to receive their values.
@app.get("/items/{item_id}/users/{user_id}"): Defines two path parametersitem_idanduser_id.def read_item(item_id: int, user_id: int):: Function parameters must match the path parameters by name and type.
python
@app.get("/items/{item_id}/users/{user_id}") def read_item(item_id: int, user_id: int): return {"item_id": item_id, "user_id": user_id}
Example
This example shows a FastAPI app with a route that accepts two path parameters: category (string) and item_id (integer). The function returns a JSON with both values.
python
from fastapi import FastAPI app = FastAPI() @app.get("/categories/{category}/items/{item_id}") def read_category_item(category: str, item_id: int): return {"category": category, "item_id": item_id}
Output
GET /categories/books/items/42
Response: {"category": "books", "item_id": 42}
Common Pitfalls
Common mistakes when using multiple path parameters include:
- Not matching the parameter names in the path and function signature exactly.
- Forgetting to specify the type for each parameter, which can cause unexpected behavior.
- Using the same name for different parameters in the path, which leads to conflicts.
Example of wrong and right usage:
python
from fastapi import FastAPI app = FastAPI() # Wrong: parameter name mismatch @app.get("/users/{user_id}/items/{item}") def read_item(user_id: int, item_id: int): # 'item_id' does not match 'item' return {"user_id": user_id, "item_id": item_id} # Right: matching names @app.get("/users/{user_id}/items/{item_id}") def read_item_correct(user_id: int, item_id: int): return {"user_id": user_id, "item_id": item_id}
Quick Reference
Tips for using multiple path parameters in FastAPI:
- Always use
{param_name}in the route path for each parameter. - Match function argument names and types exactly to the path parameters.
- Use type annotations to enable automatic data validation and conversion.
- Separate parameters with slashes
/in the path.
Key Takeaways
Define multiple path parameters by placing each inside curly braces in the route path.
Function parameters must match path parameter names and include type annotations.
Type annotations enable FastAPI to validate and convert path parameters automatically.
Parameter names must be unique and consistent between path and function signature.
Separate multiple parameters with slashes in the route path for clarity and correctness.