Skip to content
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