FastAPI Path Parameters

A path parameter is a variable part of a URL. It lets you build routes that respond differently based on what is typed in the URL. For example, one route can serve any user's profile by changing just the ID number in the address.

The Problem Path Parameters Solve

Without path parameters, you would need a separate route for every user:

/user-1    → route for user 1
/user-2    → route for user 2
/user-3    → route for user 3
... (impossible to scale)

With path parameters, one route handles all of them:

/users/{user_id}   → one route for ALL users

Your First Path Parameter

from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{user_id}")
def get_user(user_id: int):
    return {"user_id": user_id, "name": "User number " + str(user_id)}

The curly braces {user_id} in the path mark the variable spot. FastAPI passes whatever appears there to your function as the user_id argument.

URL: /users/42
             │
             └──── FastAPI extracts "42"
                   converts it to int
                   passes it to get_user(user_id=42)

Type Checking Happens Automatically

Notice user_id: int in the function signature. FastAPI enforces this type:

GET /users/42     → Works.  Returns user 42
GET /users/abc    → Fails.  Returns error: "value is not a valid integer"

You get free input validation just from writing a Python type hint. No extra code required.

String Path Parameters

Not all path parameters need to be numbers. Use str for text values like slugs or usernames:

@app.get("/products/{product_slug}")
def get_product(product_slug: str):
    return {"slug": product_slug}
URL: /products/red-running-shoes
Returns: {"slug": "red-running-shoes"}

Multiple Path Parameters in One Route

A route can contain more than one path parameter:

@app.get("/schools/{school_id}/students/{student_id}")
def get_student(school_id: int, student_id: int):
    return {
        "school": school_id,
        "student": student_id
    }
URL: /schools/5/students/101
Returns: {"school": 5, "student": 101}

Think of it like a postal address — country → city → street. Each segment narrows the location.

/schools/5
         └── school 5
/schools/5/students/101
                   └── student 101 inside school 5

Order Matters When Routes Look Similar

FastAPI reads routes from top to bottom. Put specific (fixed) routes before dynamic ones:

# CORRECT ORDER:
@app.get("/users/me")        ← specific, checked first
def get_me():
    return {"user": "current user"}

@app.get("/users/{user_id}") ← dynamic, checked second
def get_user(user_id: int):
    return {"user_id": user_id}
# WRONG ORDER:
@app.get("/users/{user_id}") ← FastAPI tries to match "me" as an int → ERROR
@app.get("/users/me")        ← never reached

Predefined Choices with Enum

If a path parameter should only accept specific values, use Python's Enum:

from enum import Enum

class Color(str, Enum):
    red = "red"
    green = "green"
    blue = "blue"

@app.get("/colors/{color_name}")
def get_color(color_name: Color):
    return {"color": color_name}
/colors/red    → works
/colors/green  → works
/colors/purple → error: not a valid choice

The docs page also shows a dropdown with only the valid options.

Key Points

  • Path parameters are variable segments in a URL wrapped in {curly_braces}.
  • FastAPI automatically extracts and type-converts them.
  • Invalid types return a clear error — no extra validation code needed.
  • Place fixed routes before dynamic ones to avoid matching conflicts.
  • Use Enum to restrict a path parameter to a set of allowed values.

Leave a Comment

Your email address will not be published. Required fields are marked *