How to Extract Query Parameters in FastAPI

Updated: November 4, 2022 By: Goodman Post a comment

A query string is the part of a URL that comes after the question mark ?. It is meant to send small amounts of information to the server via the URL. This information is usually used as parameters to paginate, filter, and sort records from a database. Query parameters (or query params) are key-value pairs in the query string that are separated by & characters. For example, if we have a URL like this:

http://localhost:8000/items?page=1&limit=10&orderBy=id&order=DESC

Then there are 4 key-value pairs of query params:

  • page: with a value of 1
  • limit: with a value of 10
  • orderBy: with a value of id
  • order: with a value of DESC (abbreviation of descending)

In FastAPI, extracting and validating query parameters is simple and straightforward. What we have to do is to declare them as arguments of the request handler function. The parameters that are not part of the path parameters will be automatically interpreted as query parameters.

We will write the code to get the query params in the URL above:

from fastapi import FastAPI

app = FastAPI()


@app.get('/items')
async def get_items(page: int, limit: int, orderBy: str, order: str):
    return {"information": {
        "page": page,
        "limit": limit,
        "orderBy": orderBy,
        "order": order
}}

Start your FastAPI app, then open your web browser and go to this URL:

http://localhost:8000/items?page=1&limit=10&orderBy=id&order=DESC

You will get this:

You can also set default values for the query parameters like this:

from fastapi import FastAPI

app = FastAPI()


@app.get('/items')
async def get_items(page: int = 0, limit: int = 10, orderBy: str = 'id', order: str = 'asc'):
    return {"information": {
        "page": page,
        "limit": limit,
        "orderBy": orderBy,
        "order": order
}}

Then, if any parameters are not explicitly listed in the URL, the default value will be used. In addition, FastAPI also validates the type of the params automatically. Another thing worth noticing is that the parameters that the user arbitrarily adds without being declared in the path operation function are also ignored. This increases the security of the application.