Skip to content

04 Path Parameters

DodaTech 4 min read

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

  1. Static route after parameterized route — /users/{id} matches /users/me before the static route. Define static routes first in code order.
  2. Missing Path import — When using Path() for validation metadata, import it from fastapi. The import is FastAPI-specific.
  3. 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.
  4. Not validating path parameters — Without validation (ge, le, min_length), path parameters can accept any value within the type range. Validate early.
  5. 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

  1. How does FastAPI convert a string URL segment to an int path parameter?
  2. What is the purpose of the Path() function?
  3. How do you validate that a path parameter is at least 1?
  4. What happens if you pass a non-numeric value to an int path parameter?
  5. 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

Can I use enum types for path parameters?

Yes, define an Enum class and use it as the type hint. FastAPI validates that the path value is a valid enum member.

What happens if path parameter validation fails?

FastAPI returns a 422 Unprocessable Entity response with details about which validation rule was violated.

How do I make a path parameter optional?

Path parameters cannot be optional because they are part of the URL structure. Use query parameters for optional values.

Can I have a path parameter with a slash?

Path parameters cannot contain slashes because the URL structure splits on slashes. Use encoded values or query parameters for such data.

What types are supported for path parameters?

str, int, float, bool, UUID, datetime, Enum, and any type that has a compat method or can be parsed from a string.

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