What are Path Parameters in FastAPI?#
Path parameters are variables that are part of the URL path. They allow you to capture values from the URL and use them inside your function.
For example, in the URL:
/items/42
42 can be captured as a path parameter.
Basic Example#
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
Explanation:#
@app.get("/items/{item_id}"): This defines a route whereitem_idis a path parameter.item_id: int: FastAPI automatically converts the path parameter to an integer.The function returns the value of
item_idas JSON.
Multiple Path Parameters#
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(user_id: int, item_id: str):
return {"user_id": user_id, "item_id": item_id}
You can define multiple parameters in the path and FastAPI will parse them accordingly.
Path Parameter with Validation#
You can also use Pydantic and Path for validation:
from fastapi import Path
@app.get("/products/{product_id}")
async def get_product(product_id: int = Path(..., gt=0, description="The ID must be greater than 0")):
return {"product_id": product_id}
gt=0: Ensures the ID is greater than 0....: Means the parameter is required.
Path Parameters vs Query Parameters#
Path parameters are part of the URL path:
/items/42Query parameters are after the
?:/items?skip=0&limit=10
Hereβs a table pattern that shows how FastAPI path parameters map URLs to functions and parameters. This can help you visualize how different URL structures correspond to function calls.
FastAPI Path Parameter Mapping Table#
URL Pattern |
Function Signature |
Path Parameters |
Example URL |
Example Output |
|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Notes:#
Use
:pathto capture the entire path including slashes.Use
Path()fromfastapito add validation (e.g.,gt=0,min_length=3).FastAPI automatically converts types based on annotations.