Path Parameters

Path parameters are variable parts of the URL path, declared with curly braces and received as function arguments. FastAPI converts and validates them using the declared type hints.

Basic Usage

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

Order Matters: Fixed Paths Before Dynamic

@app.get("/users/me")
def read_current_user():
    return {"user_id": "the current user"}

@app.get("/users/{user_id}")
def read_user(user_id: str):
    return {"user_id": user_id}

Routes are evaluated in declaration order. /users/me must be declared before /users/{user_id}, otherwise "me" would be captured as a user_id.

Enums as Constrained Values

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):
    if model_name is ModelName.alexnet:
        return {"model_name": model_name, "message": "Deep Learning FTW!"}
    return {"model_name": model_name, "message": "Have some residuals"}

Only the values alexnet, resnet, lenet are accepted; anything else returns 422 with the list of valid options.

Extra Path Validation with Path()

from fastapi import FastAPI, Path

@app.get("/items/{item_id}")
def read_item(item_id: int = Path(title="The ID of the item", ge=1, le=1000)):
    return {"item_id": item_id}

ge=1 (greater than or equal) rejects IDs like 0 or negatives; the title appears in the OpenAPI docs.

Full Path Structure with :path Converter

@app.get("/files/{file_path:path}")
def read_file(file_path: str):
    return {"file_path": file_path}

By default a parameter cannot contain slashes. The :path converter captures multi-segment paths like /files/home/user/report.pdf.

Quick Questions and Answers

Q: What error does FastAPI return for an invalid path parameter type?

A: 422 Unprocessable Entity with a JSON body listing the exact location, message and type of each validation error, e.g. {"loc": ["path", "item_id"], "msg": "value is not a valid integer"}.

Q: Can a path parameter have a default value?

A: No. Path parameters are always required because they are part of the URL structure; if you give a default, FastAPI raises an error. Only query parameters can be optional.

Q: How do I declare a parameter that could be a path segment OR come from somewhere else?

A: FastAPI resolves parameters by name in this order: path parameters first (by matching the route), then query parameters. Use Path() or Query() to be explicit when the same name appears in more than one place.

Conclusion

Path parameters let one route serve many resources. Type hints turn them into validated, documented values for free: declare int, UUID, Enum or add constraints with Path(ge=..., le=...) and FastAPI handles conversion, errors and docs.