2 Hours

5. Path Parameters & Query Parameters

Parameter Handling

In API development, data can be passed to your endpoints in three primary ways: path parameters (part of the URL path), query parameters (after the ? in the URL), and request bodies (for POST/PUT). Understanding the difference between path and query parameters is essential for RESTful API design. To test these examples, save to main.py and run uvicorn main:app --reload.

What are Path Parameters?

Path parameters are variable parts of the URL path itself. They are used to identify specific resources. For example, in /users/42, the 42 is a path parameter representing the user ID. Path parameters are required for the route to match — the URL must include them.

Python 3
from fastapi import FastAPI

app = FastAPI()

# Path parameter declared with curly braces in the path
@app.get("/users/{user_id}")
def get_user(user_id: int):
    return {"user_id": user_id, "name": f"User {user_id}"}

# Multiple path parameters
@app.get("/users/{user_id}/posts/{post_id}")
def get_post(user_id: int, post_id: int):
    return {"user_id": user_id, "post_id": post_id}
Local Testing: Visit /users/123 in your browser. FastAPI will extract 123 as the user_id parameter and pass it to your function.

Path Parameter Type Conversion

When you declare a path parameter with a type annotation (like int or float), FastAPI automatically converts the string from the URL to that type. If conversion fails, FastAPI returns a clear error message.

Python 3
# String path parameter (default)
@app.get("/items/{item_name}")
def get_item(item_name: str):
    return {"item": item_name}

# Integer path parameter
@app.get("/products/{product_id}")
def get_product(product_id: int):
    return {"product_id": product_id}

# Float path parameter
@app.get("/coordinates/{lat}/{lon}")
def get_coordinates(lat: float, lon: float):
    return {"latitude": lat, "longitude": lon}
Path Parameter Order Matters: When you have multiple path parameters, the order in the URL must match the order in your function parameters.

Path Parameter Validation

You can add validation to path parameters using the Path() function from FastAPI. This allows you to set minimum and maximum values, regex patterns, and more.

Python 3
from fastapi import FastAPI, Path

app = FastAPI()

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

@app.get("/users/{user_id}")
def get_user(
    user_id: int = Path(..., description="User identifier", gt=0, lt=10000)
):
    return {"user_id": user_id}

What are Query Parameters?

Query parameters appear after the ? in a URL. They are used for filtering, sorting, pagination, and optional parameters that are not part of the resource identifier. Unlike path parameters, query parameters are optional by default.

Python 3
# Query parameters are parameters NOT in the path
@app.get("/items")
def get_items(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

# Optional query parameter
@app.get("/users")
def get_users(active_only: bool = False):
    if active_only:
        return {"users": ["Alice", "Bob"]}
    return {"users": ["Alice", "Bob", "Charlie"]}
Local Testing: Visit /items?skip=20&limit=50 or /users?active_only=true to see query parameters in action.

Required vs Optional Query Parameters

If a query parameter has a default value, it is optional. If it has no default value, it becomes required. The client must provide it.

Python 3
# Optional query parameters (have defaults)
@app.get("/search")
def search(q: str = "", page: int = 1, limit: int = 20):
    return {"query": q, "page": page, "limit": limit}

# Required query parameter (no default)
@app.get("/products")
def get_product_by_sku(sku: str):
    return {"sku": sku, "product": f"Product {sku}"}
Local Testing: Visit /products?sku=ABC123. FastAPI will extract the sku value. Visit without sku and you will get a validation error.

Query Parameter Type Conversion and Validation

Just like path parameters, query parameters automatically convert to their declared types. Use Query() to add validation rules.

Python 3
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/items")
def get_items(
    page: int = Query(1, ge=1, description="Page number"),
    limit: int = Query(10, ge=1, le=100, description="Items per page"),
    sort_by: str = Query("id", regex="^(id|name|price)$")
):
    return {"page": page, "limit": limit, "sort_by": sort_by}

Multiple Values for a Query Parameter (Lists)

Sometimes you want to allow multiple values for the same query parameter, like ?tags=python&tags=fastapi. Use List[str] with Query() to collect them.

Python 3
from typing import List
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/articles")
def get_articles(tags: List[str] = Query([], description="Filter by tags")):
    return {"filters": {"tags": tags}}

@app.get("/products")
def get_products(categories: List[str] = Query(..., description="Required")):
    return {"categories": categories}

Combining Path and Query Parameters

You can use path and query parameters together in the same endpoint. Path parameters identify the resource, and query parameters modify the response.

Python 3
@app.get("/users/{user_id}/orders")
def get_user_orders(
    user_id: int,
    status: str = None,
    limit: int = 10,
    include_cancelled: bool = False
):
    return {"user_id": user_id, "status": status, "limit": limit}

Knowledge Check

Ready to test your understanding of 5. Path Parameters & Query Parameters?

Back