FastAPI Query Parameters

Query parameters are in the URL?after, with&Separated key-value pairs. When a function parameter is neither a path parameter nor a request body, FastAPI automatically interprets it as a query parameter.


Basic Usage

Declaring query parameters only requires adding type annotations and default values to the function parameters:

Example

from fastapi import FastAPI

app = FastAPI()

# skip and limit are query parameters with default values
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    # Mock Pagination Query
    return fake_items_db[skip : skip + limit]

The format of query parameters in the URL:

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

Parameter values for different access methods:

URLThe value of skipvalue of limitDescription
/items/010Use default value
/items/?skip=202010skip uses the passed-in value, limit uses the default value
/items/?skip=20&limit=5205Both parameters use the passed-in values

Optional parameters

Set the default value toNoneYou can declare optional query parameters:

Example

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str | None = None):
    # item_id is a path parameter (required), q is a query parameter (optional)
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

Hereq: str | None = NoneRepresentsqCan be a string orNone, the default value isNone。

FastAPI uses default values= NoneDetermines whether a parameter is required, rather than through type annotations.str | None. Type annotations mainly help editors provide better support.


Query parameter type conversion

FastAPI supports automatically converting query parameters toboolType:

Example

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: str, short: bool = False):
    # The short parameter is automatically converted to a boolean
    if short:
        return {"item_id": item_id}
    return {"item_id": item_id, "description": "This is a very long description"}

In the following URL, theshortparameters will be converted toTrue:

/items/foo?short=1
/items/foo?short=True
/items/foo?short=true
/items/foo?short=on
/items/foo?short=yes

Other values will be converted toFalse。


Required query parameter

Query parameters without default values are required parameters:

Example

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: str, needy: str):
    # needy has no default value, it is a required query parameter
    return {"item_id": item_id, "needy": needy}

If accessed/items/foowhen not providedneedyparameter, FastAPI will return an error similar to the following:

{
  "detail": [
    {
      "type": "missing",
      "loc": ["query", "needy"],
      "msg": "Field required",
      "input": null
    }
  ]
}

Mixing required, default-valued, and optional parameters

You can mix different types of query parameters in the same function:

Example

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(
    item_id: str,           # Path parameters (required)
    needy: str,             # Required Query Parameters
    skip: int = 0,          # Query parameters with default values
    limit: int | None = None,  # Optional Query Parameters
):
    item = {"item_id": item_id, "needy": needy, "skip": skip}
    if limit:
        item.update({"limit": limit})
    return item

Parameter type summary:

ParameterDeclaration methodRequired?Description
item_iditem_id: strRequiredPath parameters, appearing in the URL path
needyneedy: strRequiredQuery parameter, no default value
skipskip: int = 0OptionalQuery parameter, with default value 0
limitlimit: int | None = NoneOptionalQuery parameter, default value is None

Multiple path and query parameters

FastAPI can recognize multiple path parameters and query parameters simultaneously; the declaration order of parameters does not affect recognition:

Example

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
    user_id: int,       # Path Parameters
    item_id: str,       # Path Parameters
    q: str | None = None,  # Optional Query Parameters
    short: bool = False,   # Query parameters with default values
):
    item = {"item_id": item_id, "owner_id": user_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update({"description": "This is a very long description"})
    return item

FastAPI matches variables in the path by parameter name, so the order of function parameters does not matter.


Summary

Key points of query parameters:

  • Parameters with default values are optional, and those without default values are required.
  • FastAPI automatically converts strings in the URL to the declared type.
  • boolType supports multiple syntaxes (true、1、on、yesetc.)
  • Query parameters can be mixed with path parameters; the order does not matter.
other extensions