04 Path Parameters
title: Path Parameters in FastAPI REST APIs weight: 14 date: 2026-06-28 lastmod: 2026-06-28 description: Learn FastAPI path parameters with type validation, automatic documentation, parameter metadata, and path converters for string, int, float, and UUID types. tags: [api-development, fastapi]
FastAPI path parameters extract dynamic values from URL paths using Python type hints, automatically validating types and generating OpenAPI documentation with parameter metadata like title, description, and constraints.
```mermaid
flowchart TD
A[Path Parameter] --> B[URL Template]
B --> C[/users/{user_id}]
A --> D[Type Validation]
D --> E[int, str, uuid, float]
A --> F[Metadata]
F --> G[title, description, ge, le]
A --> H[Automatic Docs]
style A fill:#e1f5fe
style B fill:#c8e6c9
style D fill:#fff9c4
Define path parameters in the decorator path string with curly braces: /users/{user_id}. The function parameter with the same name receives the parsed value. FastAPI validates the type and converts the string to the specified Python type automatically.
Think of path parameters like apartment numbers in a building address. The street address is the base path (/users), and the apartment number is the path parameter (42). Just as apartments have specific numbers, path parameters identify specific resources.
Example: Basic Path Parameters
from fastapi import FastAPI
from uuid import UUID
app = FastAPI()
@app.get("/api/users/{user_id}")
def get_user(user_id: int):
"""Parameter validated as int."""
return {"user_id": user_id, "type": "integer"}
@app.get("/api/orders/{order_uuid}")
def get_order(order_uuid: UUID):
"""Auto-validated as UUID."""
return {"order_id": str(order_uuid), "type": "uuid"}
@app.get("/api/items/{item_id}/versions/{version_id}")
def get_item_version(item_id: int, version_id: int):
"""Multiple path parameters."""
return {
"item_id": item_id,
"version_id": version_id
}
# GET /api/users/42 -> {"user_id": 42}
# GET /api/orders/550e8400-e29b-41d4-a716-446655440000 -> UUID
# GET /api/items/5/versions/2 -> {"item_id": 5, "version_id": 2}
Example: Path Parameter Validation and Metadata
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/api/products/{product_id}")
def get_product(
product_id: int = Path(
...,
title="Product ID",
description="The unique identifier of the product",
ge=1, # Greater than or equal to 1
le=10000 # Less than or equal to 10000
)
):
return {"product_id": product_id}
@app.get("/api/users/{username}")
def get_user_by_username(
username: str = Path(
...,
title="Username",
description="Username must be 3-50 alphanumeric characters",
min_length=3,
max_length=50,
pattern="^[a-zA-Z0-9_]+$"
)
):
return {"username": username}
# Invalid: GET /api/products/0 -> 422 Validation Error
# Invalid: GET /api/users/ab -> 422 (too short)
Example: Path Parameter Order and Precedence
from fastapi import FastAPI
app = FastAPI()
# Static route MUST come before parameterized
@app.get("/api/users/me")
def get_me():
return {"user": "current"}
@app.get("/api/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}
@app.get("/api/users/{user_id}/posts")
def get_user_posts(user_id: int):
return {"user_id": user_id, "posts": ["post1", "post2"]}
@app.get("/api/users/{user_id}/posts/{post_id}")
def get_user_post(user_id: int, post_id: int):
return {"user_id": user_id, "post_id": post_id}
Common Mistakes
- Static route after parameterized route — /users/{id} matches /users/me before the static route. Define static routes first in code order.
- Missing Path import — When using Path() for validation metadata, import it from fastapi. The import is FastAPI-specific.
- Wrong type for path parameters — Path parameters are always strings from the URL. FastAPI converts them to the declared type, which may fail for incompatible values.
- Not validating path parameters — Without validation (ge, le, min_length), path parameters can accept any value within the type range. Validate early.
- Multiple path parameters with the same name — Each path parameter must have a unique name that matches a function parameter. Duplicates cause errors.
Practice Questions
- How does FastAPI convert a string URL segment to an int path parameter?
- What is the purpose of the Path() function?
- How do you validate that a path parameter is at least 1?
- What happens if you pass a non-numeric value to an int path parameter?
- Challenge: Create a blog API with path parameters for author ID, post ID, and comment ID. Add validation: author_id >= 1, post_id >= 1, comment_id >= 1. Include a static route /authors/me before parameterized routes.
FAQ
Mini Project
Build an e-commerce API with path parameters for categories, products, and variants. Include validation: category ID (1-100), product ID (UUID), variant SKU (string, 5-20 chars, pattern: ^[A-Z0-9-]+$). Add a static route /categories/latest before parameterized routes.
What's Next
Now learn about query parameters in Building REST APIs with FastAPI.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro