FastAPI by Example: Path Parameter Types
Path parameters are parts of the URL path that are variable. This sample code demonstrates how to define them with type hints to get automatic data validation and conversion.
Code
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(
item_id: int = Path(title="The ID of the item to get", ge=1)
):
# item_id is automatically converted to an int
return {"item_id": item_id}
@app.get("/users/{user_name}")
async def read_user(user_name: str):
# user_name is a string
return {"user_name": user_name}
@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
# :path converter allows matching slashes
return {"file_path": file_path}Explanation
FastAPI leverages Python type hints to perform automatic request parsing and validation for path parameters. When a path operation function declares a parameter with a type like integer or string, the framework attempts to convert the raw URL segment into that specific Python type. If the conversion fails, such as passing a non-numeric string for an integer parameter, FastAPI automatically generates a 422 Unprocessable Entity error response with details about the validation failure. Key features of using path parameters include:
- Dynamic Routing: Capture variable values directly from the URL path for flexible route definitions.
- Readable URLs: Create clean, intuitive, and human-readable API endpoints.
- Automatic Validation: Leverage Python type hints for automatic data conversion and error handling.
Advanced use cases often require capturing path segments that contain slashes, which is handled by the Starlette path converter. By specifying a path type in the route definition, the parameter can match the remaining path segments, making it suitable for file paths or hierarchical resources. This mechanism bypasses the standard behavior where slashes act as delimiters, allowing for flexible URL structures.
Code Breakdown
item_id: int tells FastAPI to read the item_id from the URL and convert it to an integer.Path(..., ge=1) adds extra validation. ge=1 means "greater than or equal to 1".{file_path:path} uses the Starlette path converter to capture full paths including slashes.return {"item_id": item_id} demonstrates that the variable is accessible as a native integer.
