Query Parameters and Path Variables: Building Dynamic FastAPI APIs
Master dynamic API design in FastAPI. Learn to use path variables for unique resource routing and query parameters for data filtering in your Python backend.

Previously in this course, we learned how to set up our web server and define basic routes in Introduction to Web Frameworks and Defining API Endpoints. Those lessons focused on static endpoints; today, we add interactivity by making our API endpoints dynamic.
In production, you rarely want an endpoint that returns the exact same data every time. You need to identify specific resources (like a user ID) or filter results (like searching for items by name). We achieve this using Path Variables and Query Parameters.
Understanding Path Variables vs. Query Parameters
While both allow a client to send data to your server, they serve different architectural purposes.
| Feature | Path Variable | Query Parameter |
|---|---|---|
| Syntax | /items/{id} | /items?category=books |
| Use Case | Identifying a specific resource | Filtering, sorting, or pagination |
| Requirement | Required (part of the URL) | Usually optional |
When designing your API, a good rule of thumb is: use path variables for the "what" (the resource) and query parameters for the "how" (how the result set should be modified).
Implementing Path Variables
Path variables are embedded directly into the URL path. In FastAPI, we define these using curly braces {} in the route decorator, then capture them as function arguments.
PYTHONfrom fastapi import FastAPI app = FastAPI() # Example: Fetching a specific user by ID @app.get("/users/{user_id}") def get_user(user_id: int): return {"user_id": user_id, "name": "Standard User"}
When a user visits /users/42, FastAPI automatically extracts 42, converts it to an integer (thanks to our type hint), and passes it to the get_user function.
Adding Query Parameters for Filtering
Query parameters appear after the ? in a URL. In FastAPI, any argument in your function that is not part of the path is automatically treated as a query parameter.
Let's expand our project to filter a list of data.
PYTHON# Simulated database items = [ {"id": 1, "name": "Laptop", "category": "electronics"}, {"id": 2, "name": "Coffee Mug", "category": "kitchen"}, {"id": 3, "name": "Headphones", "category": "electronics"} ] @app.get("/items") def list_items(category: str = None): if category: # Use list comprehension to filter the data return [item for item in items if item["category"] == category] return items
In this example, calling /items returns the full list. Calling /items?category=electronics triggers the filter logic, returning only the electronics.
Hands-on Exercise: Dynamic Search
Update your existing project's API to include a "search" feature.
- Create an endpoint
/products/{product_id}that returns a single product from your data list based on its ID. - Add a query parameter
min_priceto a/productsendpoint to filter items that cost more than a specific value. - Test your endpoints using your browser or a tool like
curlas discussed in Testing API Endpoints: Manual Validation with cURL and Postman.
Common Pitfalls
- Type Mismatch: If you expect an
intin a path variable but the user provides a string, FastAPI will automatically return a422 Unprocessable Entityerror. This is a feature, not a bug—it keeps your backend secure. - Conflicting Routes: If you define
/items/latestand/items/{item_id}, FastAPI might get confused. Always define static routes before routes with path variables. - Default Values: Remember that query parameters are optional by default if you assign a default value (e.g.,
limit: int = 10). If you want to make a query parameter mandatory, simply don't provide a default value.
Frequently Asked Questions
Can I use multiple query parameters?
Yes. Simply add more arguments to your function (e.g., def list_items(category: str = None, limit: int = 10):). FastAPI will pick them all up from the URL.
What happens if a query parameter is missing?
If you define a default value (like None), the parameter will be None inside your function. If you don't define a default, FastAPI will require the client to provide it, or it will return an error.
Recap
We've moved from static responses to dynamic data handling. By using path variables, we can target specific resource IDs, and by using query parameters, we can implement powerful filtering features like those explored in Introduction to Query Parameters: Modifying API Behavior. These techniques are the bedrock of any professional RESTful API.
Up next: We will begin our journey into Object-Oriented Programming (OOP) to better structure our data-heavy applications.
Work with me

Laravel REST API Development
Clean, secure, well-documented Laravel REST APIs — the backend engine for your app, mobile client, or SaaS. Built by an API specialist.

Next.js Full-Stack Web App Development
A fast, SEO-ready full-stack web app built with Next.js 16 — from idea to deployed product, by an engineer who ships to production.


