← Back to Tutorials

9. Path Parameters

from fastapi import FastAPI

app = FastAPI()

# Path parameter with type
@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

# Multiple path params
@app.get("/users/{user_id}/orders/{order_id}")
def get_order(user_id: int, order_id: int):
    return {"user_id": user_id, "order_id": order_id}

# Path parameter order matters — static before dynamic
@app.get("/users/me")           # static
def get_current_user(): ...

@app.get("/users/{user_id}")    # dynamic
def get_user(user_id: int): ...

# Enum path parameter
from enum import Enum

class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"

@app.get("/models/{model_name}")
def get_model(model_name: ModelName):
    return {"model": model_name}
✏️ Exercise: Create endpoints with path parameters for a library API: /books/{book_id}, /authors/{author_id}/books/{book_id}. Test them in Swagger UI.