FastAPI
Path Parameters
Capture typed path segments with validation.
By EZ4Code Team
pathparams
Code
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
def read_user(user_id: int):
return {"user_id": user_id}
@app.get("/files/{file_path:path}")
def read_file(file_path: str):
return {"file_path": file_path}
@app.get("/items/{item_id}")
def read_item(item_id: str, q: str | None = None):
return {"item_id": item_id, "q": q}Explanation
Path parameters declared in the route are passed to the handler with the same name and validated against the type annotation. The :path converter captures slashes for nested file paths. Optional query params use a default of None with a union type.
More FastAPI Snippets
Query Parameters
Parse query strings with defaults and validation.
Pydantic Request Body
Validate JSON bodies with Pydantic models.
Dependency Injection
Share logic via Depends and yield-based dependencies.
Response Model
Shape and filter responses with response_model.
JWT Auth
Issue and verify JSON Web Tokens with OAuth2.
Async and Await
Define async handlers and run blocking work in a thread.