Query Parameters: Filtering and Pagination

Query Parameters: Filtering and Pagination

Master optional parameters in FastAPI. Learn how to handle defaults, required query params, and data validation.

Query Parameters: Filtering and Pagination

While Path Parameters are used to identify a specific resource (like a specific user), Query Parameters are used for everything else: filtering, sorting, searching, and pagination.

In this lesson, we learn how to handle the optional side of requests.


1. What is a Query Parameter?

A query parameter is the part of the URL that comes after the ?. Example: /items/?skip=0&limit=10

In FastAPI, any function argument that is not part of the path is automatically interpreted as a query parameter.

from typing import Optional

@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

2. Optional vs. Required Parameters

Unlike Path Parameters (which are always required), Query Parameters can be optional.

  • Required: If you don't provide a default value, it is required.
    • async def read(page: int)
  • Optional (with default): The most common pattern.
    • async def read(page: int = 1)
  • Purely Optional: Use Optional from the typing module.
    • async def read(q: Optional[str] = None)

3. Data Validation with Query

FastAPI provides a Query helper that allows you to add extra validation to your parameters without cluttering your logic.

from fastapi import Query

@app.get("/search/")
async def search(
    q: str = Query(None, min_length=3, max_length=50, pattern="^[a-zA-Z]+$")
):
    return {"query": q}

If a user searches for "a", FastAPI sends back an error: "String should have at least 3 characters."


4. Multiple Values (Lists)

Sometimes you want to allow a user to filter by multiple categories at once. Example: /items/?q=foo&q=bar

from typing import List

@app.get("/items/")
async def read_items(q: List[str] = Query([])):
    return {"query_list": q}

Comparison: Path vs. Query

FeaturePath ParameterQuery Parameter
Location/users/{id}?limit=10
RequirementAlways RequiredUsually Optional
Primary UseIdentification (The "Noun")Filtering/Options (The "Adjective")

Summary

  • Any argument not in the path is a query parameter.
  • Default values determine if a parameter is optional.
  • The Query class allows for powerful validation like min_length or Regex patterns.
  • Lists can be received by typing the parameter as List[str].

In the next lesson, we move to the "Heavy Lifting": Request Bodies and JSON Payloads.


Exercise: The Search Bar

Imagine you are building a search endpoint. You want to allow the user to search for a term (q), but only if it's longer than 2 characters. If they don't provide a term, return all results. How would you define that function signature?

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn