Sling Academy
Home/FastAPI/How to Extract Query Parameters in FastAPI

How to Extract Query Parameters in FastAPI

Last updated: November 04, 2022

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.

Next Article: Serving Static Files in FastAPI: Tutorial & Example

Previous Article: How to Use Dynamic Routes in FastAPI

Series: FastAPI Tutorials for Beginners

FastAPI

You May Also Like

  • Popular useful built-in Jinja filters you should know
  • How to remove consecutive whitespace in rendered Jinja pages
  • How to format large numbers with thousand separators in Jinja template
  • How to format date time in Jinja templates
  • FastAPI + Jinja: How to create custom filters
  • How to pass variables from Python (FastAPI) to Jinja
  • How to decode Jinja response to string
  • How to create and use macros in Jinja
  • How to use namespace in Jinja
  • How to use if/ else in Jinja
  • How to use loops in Jinja
  • FastAPI + SQLAlchemy: Using cursor-based pagination
  • FastAPI: How to use macros in Jinja templates
  • Fixing Common Swagger UI Errors in FastAPI
  • FastAPI Error: 307 Temporary Redirect – Causes and Solutions
  • FastAPI Error: Expected UploadFile, received ‘str’
  • Resolving FastAPI ImportError: No Known Parent Package
  • FastAPI Error: No module named ‘pydantic_core._pydantic_core’
  • Resolving FastAPI 422 Error: Value is not a valid dict