FastAPI Path Parameters: A Complete Guide

Learn how to use and validate path parameters in FastAPI applications

Beginner 25 min Tutorial 4 steps

Overview

Developers new to FastAPI often struggle with how to properly declare and validate path parameters in their API endpoints.

What You'll Learn:

  • How to declare basic path parameters in FastAPI
  • How to add type validation and constraints to path parameters
  • Best practices for organizing and documenting path parameters
1

Understanding Path Parameters

Estimated: 5 min

Path parameters are variable parts of a URL path that FastAPI can capture and use in your endpoint functions. They allow you to create dynamic routes that respond to different values in the URL. For example, in a URL like `/users/123`, the `123` part could be a path parameter representing a user ID.

info

Path parameters are defined using curly braces in the path decorator

tip

Path parameters are required by default - the endpoint won't match if they're missing

main.py
from fastapi import FastAPI

app = FastAPI()

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

This example shows a basic path parameter `item_id` that FastAPI will capture from the URL and pass to the function.

2

Adding Type Validation to Path Parameters

Estimated: 8 min

FastAPI automatically validates path parameters based on their type hints. This means you can declare a parameter as an integer, and FastAPI will ensure the URL contains a valid integer value before calling your endpoint function.

main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id, "item_type": type(item_id).__name__}

By adding `: int` to the parameter declaration, FastAPI will automatically convert the path parameter to an integer and return a 422 error if the value isn't a valid integer.

Quick Check

What happens if a user accesses `/items/abc` when the path parameter is declared as `item_id: int`?

3

Adding Constraints to Path Parameters

Estimated: 7 min

FastAPI allows you to add additional constraints to path parameters using Pydantic's Path class. This lets you define minimum/maximum values, length constraints, regex patterns, and more.

warning

The ellipsis (...) as the first argument to Path() indicates that the parameter is required

tip

You can use multiple constraints together, such as min_length, max_length, and regex for string parameters

main.py
from fastapi import FastAPI, Path, Query

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, le=1000)
):
    return {"item_id": item_id}

This example adds constraints to ensure `item_id` is between 1 and 1000. The `ge=1` means greater than or equal to 1, and `le=1000` means less than or equal to 1000.

Choose your approach:

String Parameter Constraints

Example of constraining a string path parameter

python
from fastapi import FastAPI, Path
import re

app = FastAPI()

@app.get("/users/{username}")
async def get_user(
    username: str = Path(
        ..., 
        min_length=3, 
        max_length=20, 
        regex="^[a-zA-Z0-9_]+$"
    )
):
    return {"username": username}
4

Working with Multiple Path Parameters

Estimated: 5 min

FastAPI allows you to use multiple path parameters in a single route. This is useful for creating nested resource structures like `/users/{user_id}/posts/{post_id}`.

tip

The order of path parameters in the function doesn't need to match their order in the URL path

info

You can mix path parameters with query parameters in the same function

main.py
from fastapi import FastAPI, Path

app = FastAPI()

@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
    user_id: int, 
    item_id: str, 
    q: str | None = None
):
    return {"user_id": user_id, "item_id": item_id, "q": q}

This example captures both a user_id and item_id from the URL path, plus an optional query parameter.