0
0
FastapiComparisonBeginner · 4 min read

Path Parameter vs Query Parameter in FastAPI: Key Differences and Usage

In FastAPI, path parameters are part of the URL path and are required to identify a specific resource, while query parameters are optional key-value pairs appended after a question mark in the URL to filter or modify the request. Path parameters define the route structure, and query parameters provide additional data without changing the route.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of path parameters and query parameters in FastAPI.

FactorPath ParameterQuery Parameter
Location in URLPart of the URL path (e.g., /items/{id})After the ? in URL (e.g., /items?id=5)
Required or OptionalAlways required to match the routeOptional by default
PurposeIdentify specific resource or entityFilter, sort, or provide extra info
Syntax in FastAPIDeclared in route path stringDeclared as function parameters with default values
Effect on RoutingDefines unique route pathsDoes not affect route matching
Example URL/users/123/users?age=30&active=true
⚖️

Key Differences

Path parameters are embedded directly in the URL path and are essential for routing. FastAPI uses them to capture values from the URL and pass them as arguments to your function. Because they are part of the route, they must always be provided by the client, or the route won't match.

On the other hand, query parameters come after the question mark in the URL and are typically optional. They are used to send additional data that can modify the response, like filtering or pagination. FastAPI treats them as function parameters with default values or optional types, so they don't affect which route is chosen.

In summary, path parameters define the structure and identity of the resource you want, while query parameters provide extra instructions or filters without changing the route itself.

⚖️

Code Comparison

This example shows how to use a path parameter in FastAPI to get an item by its ID.

python
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id, "description": "This is the item with the given ID."}
Output
{"item_id": 5, "description": "This is the item with the given ID."} (when accessed at /items/5)
↔️

Query Parameter Equivalent

This example shows how to use a query parameter in FastAPI to filter items by a minimum price.

python
from fastapi import FastAPI
from typing import Optional

app = FastAPI()

@app.get("/items/")
async def read_items(min_price: Optional[float] = None):
    if min_price is not None:
        return {"min_price": min_price, "items": "Filtered items with price >= min_price"}
    return {"items": "All items"}
Output
{"min_price": 10.5, "items": "Filtered items with price >= min_price"} (when accessed at /items/?min_price=10.5)
🎯

When to Use Which

Choose path parameters when you need to specify a unique resource or entity, such as an item ID or username, because they define the route and are required.

Choose query parameters when you want to provide optional filters, sorting options, or additional data that modifies the response without changing the route, like pagination or search terms.

Using the right parameter type helps keep your API clear, predictable, and easy to use.

Key Takeaways

Path parameters are required parts of the URL path that identify specific resources.
Query parameters are optional and provide extra data to filter or modify responses.
Path parameters affect route matching; query parameters do not.
Use path parameters for resource identity and query parameters for filtering or options.
FastAPI handles path parameters in the route string and query parameters as function arguments with defaults.