How to Use Path Parameter in FastAPI: Simple Guide
In FastAPI, you use
path parameters by adding variables inside the route path in curly braces, like /items/{item_id}. These variables are then passed as function arguments to your endpoint handler, allowing you to capture dynamic parts of the URL.Syntax
To use a path parameter in FastAPI, define it inside curly braces {} in the route path. Then, add a function parameter with the same name to receive the value from the URL.
- Route path: Use
/resource/{parameter_name}to declare a path parameter. - Function argument: The parameter name in the function matches the path parameter name.
- Type hinting: You can specify the expected type (e.g.,
int,str) for automatic validation and conversion.
python
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id}
Example
This example shows a FastAPI app with a path parameter item_id that accepts an integer. When you visit /items/5, it returns the item ID as JSON.
python
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id} # Run with: uvicorn filename:app --reload
Output
{"item_id": 5}
Common Pitfalls
Common mistakes when using path parameters include:
- Not matching the function parameter name with the path parameter name.
- Forgetting to specify the type, which can lead to unexpected string values.
- Using query parameters syntax instead of path parameters.
Example of a wrong and right way:
python
# Wrong: parameter name mismatch from fastapi import FastAPI app = FastAPI() @app.get("/users/{user_id}") async def get_user(id: int): # 'id' does not match 'user_id' return {"user_id": id} # Right: @app.get("/users/{user_id}") async def get_user(user_id: int): return {"user_id": user_id}
Quick Reference
Summary tips for using path parameters in FastAPI:
| Tip | Description |
|---|---|
| Use curly braces in path | Declare path parameters like /items/{item_id} |
| Match function parameter name | Function argument must have the same name as path parameter |
| Use type hints | Specify type (int, str) for validation and conversion |
| Path parameters are required | They must be present in the URL, unlike query parameters |
| Multiple path parameters | You can have more than one, e.g., /users/{user_id}/items/{item_id} |
Key Takeaways
Define path parameters inside curly braces in the route path.
Match the function argument name exactly to the path parameter name.
Use type hints to ensure correct data types and automatic validation.
Path parameters are mandatory parts of the URL and must be provided.
You can use multiple path parameters in a single route for complex URLs.