Skip to content

Query Parameters

We have seen how paths select resources: /posts identifies the list, and /posts/1 identifies post 1.

After choosing a resource, you may still need additional retrieval criteria. For example, you might search for Python posts or request the newest posts first.

Append ? to the path to send these options. /posts/search?topic=python searches for Python posts. /posts/search is the path; topic=python is the query string.

Could we use /posts/search/python instead? Yes, for a topic-only search. But retrieval criteria often vary. Query strings let clients choose or combine options without changing the path.

Use ?topic=python to search by topic, or ?author=alex to search by author on the same /posts/search path. Combine them with &, as in ?topic=python&author=alex. One search endpoint can then support more options while keeping the API structure simple.

Google Search URLs

Google also sends search terms in a query string at /search. Open https://www.google.com/search?q=python, then change python to fastapi to see how the results change.

Declaring Query Parameters

FastAPI uses query parameters to receive query string values. In topic=python, topic is the parameter name and python its value.

Declare query parameters as function parameters, just like path parameters.

main.py
@app.get("/posts/search", summary="Search posts")
def search_posts_handler(topic: str):  # ①
    return {"topic": topic}  # ②

Add this code directly below get_posts_handler in main.py.

Save and open http://127.0.0.1:8000/posts/search?topic=python. FastAPI passes python to topic in ①. ② returns that value in the response:

{"topic": "python"}

How does FastAPI distinguish the two kinds of parameters? It first checks whether a parameter name appears as {name} in the route.

  • A path parameter receives the value at that position. With @app.get("/posts/{post_id}"), /posts/1 passes integer 1 to the annotated post_id parameter.
  • A query parameter reads a matching name after ?. @app.get("/posts/search") has no {topic}, so topic: str is treated as a query parameter. /posts/search?topic=python passes "python" to it.

The client must use the declared name, topic. A request to /posts/search?q=python omits the required topic parameter, so FastAPI returns 422.

Route Order

The order of definitions in main.py matters. FastAPI checks routes in registration order.

For each request, it compares the method and path with each route. The first matching route handles the request.

What if /posts/{post_id} is registered before /posts/search? The path /posts/search matches the dynamic pattern first: it starts with /posts/ and has one more segment. search can occupy that segment.

The post_id: int annotation is applied after route matching. FastAPI therefore attempts to convert search to an integer and returns 422 before calling the handler.

A search request matches a dynamic post route when that route is registered first

When two routes can match the same path, register the fixed route before the dynamic one. Here, put /posts/search before /posts/{post_id} so search requests reach the search handler.

Restricting Query Length

Just as Path constrains path values, Query adds validation to query values. Let's require a search term between 2 and 20 characters.

Add Query to the import at the top of main.py:

main.py
from fastapi import FastAPI, Path, Query

Then apply it to the topic parameter of search_posts_handler:

main.py
@app.get("/posts/search", summary="Search posts")
def search_posts_handler(topic: str = Query(min_length=2, max_length=20)):
    return {"topic": topic}

min_length=2 means at least 2 characters, and max_length=20 means at most 20. FastAPI checks both before running the function.

Save and request /posts/search?topic=python again. Its six characters pass validation. Change topic=python to topic=p; the single character is too short, so the response is 422.

Check Your Understanding

Decide whether each statement is true or false.

  1. In a URL, ? separates the path from the query string, and & separates query parameters.
  2. A string parameter absent from the route pattern is automatically a path parameter.
  3. Omitting a required query parameter produces a validation error.
  4. A fixed route always takes precedence over a matching dynamic route, regardless of registration order.
  5. Minimum and maximum string lengths include their boundary values.
Answers and Explanations
  1. True — Query parameters follow ? and are separated with &.
  2. False — A simple parameter absent from the path is normally treated as a query parameter.
  3. True — The request must include required parameters using their declared names.
  4. False — Routes are checked in order. Register fixed paths before overlapping dynamic ones.
  5. True — A value exactly at either limit is allowed.