5. Path Parameters & Query Parameters
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.
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}
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.
# 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 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.
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.
# 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"]}
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.
# 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}"}
Query Parameter Type Conversion and Validation
Just like path parameters, query parameters automatically convert to their declared types. Use Query() to add validation rules.
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.
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.
@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?