Back to Blog
Lesson 44 of the Python: Programming from Zero with Python course
PythonSeptember 1, 20264 min read

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.

PythonFastAPIAPIWeb DevelopmentBackendQuery Parameters
Close-up of a computer screen displaying colorful programming code in JavaScript.

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.

FeaturePath VariableQuery Parameter
Syntax/items/{id}/items?category=books
Use CaseIdentifying a specific resourceFiltering, sorting, or pagination
RequirementRequired (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.

PYTHON
from 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.

  1. Create an endpoint /products/{product_id} that returns a single product from your data list based on its ID.
  2. Add a query parameter min_price to a /products endpoint to filter items that cost more than a specific value.
  3. Test your endpoints using your browser or a tool like curl as discussed in Testing API Endpoints: Manual Validation with cURL and Postman.

Common Pitfalls

  • Type Mismatch: If you expect an int in a path variable but the user provides a string, FastAPI will automatically return a 422 Unprocessable Entity error. This is a feature, not a bug—it keeps your backend secure.
  • Conflicting Routes: If you define /items/latest and /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.

Similar Posts