CS504070 - FastAPI Tutorials
  • 🧩CS504070 - FastAPI Tutorials
  • 🔎Unit 1: Python Type Hint
  • ⚙️Unit 2: Pydantic
  • 🔃Unit 3: Concurrency
  • 💾Unit 4: Install FastAPI
  • 🍉Unit 5: Hello World!
  • 🍌Unit 6: Path Parameters
  • 🍋Unit 7: Query Parameters
  • 🍊Unit 8: Request Body
  • 🍐Unit 9: Query Parameters and Validations
  • 🍎Unit 10: Path Parameters and Validations
  • 🍏Unit 11: Multiple Parameters
  • 🍇Unit 12: Request Body - List Fields and Nested Models
  • 🍓Unit 13: Data Types
  • 🍪Unit 14: Cookie Parameters
  • 🫐Unit 15: Header Parameters
  • 🍈Unit 16: Response Model - Return Type
  • 🍒Unit 17: Additional Models
  • 🥑Unit 18: Implementing JWT Authentication with FastAPI
  • ⚙️Appendix A
  • 🍭Appendix B
Powered by GitBook
On this page
  • Introduction
  • Query parameters
  • Optional parameters
  • Query parameter type conversion
  • Multiple path and query parameters
  • Required query parameters
  • API Docs
  • Summary

Unit 7: Query Parameters

Introduction

Query parameters are a fundamental aspect of web development, enabling the passing of optional or required information in GET requests to the server. They are appended to the URL following a ? symbol and can be used to filter results, specify the nature of a request, or provide additional data without changing the route of the request.


Query parameters

To define query parameters in FastAPI, you simply declare them as function arguments in your path operation functions. FastAPI automatically recognizes them as query parameters if they are not part of the path parameters. This is elegantly handled with Python's type hints, allowing developers to specify the data type of each query parameter, which FastAPI uses to validate incoming requests.

from fastapi import FastAPI

app = FastAPI()

sample_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 100):
    return sample_items_db[skip: skip + limit]

To evaluate the above program, you can visit the following two URLs:

  • http://127.0.0.1:8000/items/

  • http://127.0.0.1:8000/items/?skip=0&limit=2

For the first URL, the program will automatically set skip=0 and limit=100 because we've defined these default values in the parameters of the read_item() function. For the second URL, the result is as follows, due to the query parameters being set to skip=0 and limit=100.

[
    {
        "item_name": "Foo"
    },
    {
        "item_name": "Bar"
    }
]

Optional parameters

FastAPI can distinguish the path parameters and query parameters in the same function, such as follows:

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str | None = None):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

In the above program, q is an optional query parameter by setting their default to None.

Query parameter type conversion

Let's take a look at the following program:

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str | None = None, short: bool = False):
    item = {"item_id": item_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is a long description"}
        )
    return item

The following URLs will result in the same output:

  • http://127.0.0.1:8000/items/foo?short=1

  • http://127.0.0.1:8000/items/foo?short=True

  • http://127.0.0.1:8000/items/foo?short=true

  • http://127.0.0.1:8000/items/foo?short=on

  • http://127.0.0.1:8000/items/foo?short=yes

Multiple path and query parameters

You can declare multiple path parameters and query parameters at the same time, FastAPI knows which is which.

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
    user_id: int, item_id: str, q: str | None = None, short: bool = False
):
    item = {"item_id": item_id, "owner_id": user_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is a long description"}
        )
    return item

Required query parameters

When you declare a default value for non-path parameters such as query parameters, then it is not required. If you don't want to add a specific value but just make it optional, set the default as None. But when you want to make a query parameter required, you can just not declare any default value.

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def get_item(item_id: str, short: bool):
    output = {"item_id": item_id, "short": short}
    return output

When you visit http://127.0.0.1:8000/items/foo, you will encounter the following error due to the missing short parameter in the URL.

{
    "detail": [
        {
            "type": "missing",
            "loc": [
                "query",
                "short"
            ],
            "msg": "Field required",
            "input": null,
            "url": "https://errors.pydantic.dev/2.5/v/missing"
        }
    ]
}

API Docs

Once again, FastAPI can generate API Docs in both Swagger and ReDoc which are available at the following URLs:


Summary

Query parameters in FastAPI are a powerful and flexible way to add functionality to your API endpoints. By leveraging Python type hints and FastAPI's intuitive design, developers can easily define, validate, and document query parameters, resulting in robust, efficient, and easy-to-use APIs.

PreviousUnit 6: Path ParametersNextUnit 8: Request Body

Last updated 1 year ago

http://127.0.0.1:8000/docs/
http://127.0.0.1:8000/redoc
🍋
Page cover image