Path parameters and query parameters
Path Parameters vs Query Parameters in FastAPI (with Examples)
Introduction
When building APIs with FastAPI, you’ll often need to pass information from a client (like a browser or frontend app) to your backend. Two common ways to do this are:
-
Path parameters → part of the URL path
-
Query parameters → key-value pairs after a
?in the URL
Understanding when to use each is important for designing clean, user-friendly APIs
What Are Path Parameters?
Path parameters are embedded directly into the URL path. They usually identify a specific resource.
/users/123
Here:
-
123is a path parameter → it identifies a specific user.
FastAPI Example: Path Parameter
from fastapi import FastAPI
app = FastAPI()
# Define a path parameter
@app.get("/users/{user_id}")
def read_user(user_id: int):
return {"user_id": user_id}
✅ Visiting http://127.0.0.1:8000/users/123 will return:
{"user_id": 123}
Path parameters are great for identifying specific items like users, products, or orders.
What Are Query Parameters?
Query parameters appear after the ? in the URL, and they’re often used to filter, search, or paginate results.
For example:
/products?category=books&limit=10
Here:
-
category=books→ filter by books -
limit=10→ return only 10 results
FastAPI Example: Query Parameters
from fastapi import FastAPI
app = FastAPI()
# Define query parameters
@app.get("/products/")
def read_products(category: str = None, limit: int = 10):
return {"category": category, "limit": limit}
✅ Visiting http://127.0.0.1:8000/products?category=books&limit=5 will return:
{"category": "books", "limit": 5}
Query parameters are flexible and optional, making them perfect for filters, sorting, and pagination.
