tezvyn:

FastAPI Query Parameters: Beyond the URL Path

AI-drafted, machine-checkedSource: fastapi.tiangolo.combeginner

In FastAPI, function arguments not in the URL path become query parameters—the optional key-value pairs after a URL's `?`. Use them for filtering or pagination, like `/items?skip=0&limit=10`. The footgun: omitting a default value makes the parameter required.

WHY IT EXISTS: APIs need a way to accept optional data that doesn't belong in the core resource path. Controls for pagination (page=2), filtering (status=active), or sorting (sort=asc) are not part of the resource's identity. Query parameters provide a standard, flexible way to supply this information.

THE MENTAL MODEL: Think of a FastAPI function's signature as a contract for the request. Path parameters are the required, structural parts of the URL. Any other typed arguments you add to the function are automatically treated as query parameters—the knobs and dials a client can use to refine a request.

HOW IT WORKS: When you define a path operation like @app.get("/users") with a function async def get_users(is_active: bool = True):, FastAPI knows is_active is not in the path. It looks for it in the query string of an incoming request, like /users?is_active=false. It then validates the data, converts its type (from string "false" to boolean False), and passes it to your function. Providing a default value (= True) makes the parameter optional. If you omit the default, the parameter becomes required.

WHEN TO USE IT: Use query parameters for anything that modifies or filters a collection of resources. This includes pagination (skip, limit, page), filtering (status=published, author_id=123), and sorting (sort_by=created_at, order=desc). It's the go-to mechanism for optional inputs on GET requests.

WHEN NOT TO USE IT: Do not use query parameters for identifying a specific, single resource; that's what path parameters are for (e.g., /users/123, not /users?id=123). Avoid them for complex or sensitive data; use the request body for that, typically with POST or PUT requests. Sending a large JSON object as a query parameter is unwieldy and not standard practice.

ONE CANONICAL EXAMPLE: A common use case is paginating a list of items. A request to /items?skip=20&limit=10 would fetch the third page of items, assuming 10 items per page. The FastAPI function would be async def read_item(skip: int = 0, limit: int = 10):. FastAPI handles parsing skip and limit from the URL, converting them to integers, and passing them to your function.

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.