Path parameters vs query parameters

Difficulty: Beginner

Question

How does FastAPI tell path parameters apart from query parameters, and how do you declare required and optional ones?

Answer

FastAPI decides by looking at the route path and the function signature. If a parameter name appears inside {} in the path, it is a path parameter and is always required. Any other simple-typed parameter (int, str, bool, enum, etc.) is treated as a query parameter: it is required if it has no default and optional if it has one.

The decision rules

When FastAPI inspects a handler, each parameter is classified like this:

  1. Name matches a {placeholder} in the path: path parameter.
  2. Type is a Pydantic model (and not wrapped in Query): request body.
  3. Type is a singular type such as int, str, float, bool, UUID, date or an Enum: query parameter.
  4. Explicit markers override inference: Query(), Path(), Body(), Header(), Cookie().
DeclarationWhere it comes fromRequired?
order_id: int with /orders/{order_id}PathAlways
status: strQuery stringYes, no default
limit: int = 20Query stringNo, defaults to 20
`q: str \None = None`Query stringNo, may be None

Type conversion and validation

Everything in a URL is a string. FastAPI converts it using the type hint:

  • /orders/42 with order_id: int gives you the integer 42; /orders/abc returns a 422.
  • bool query params accept true, 1, yes, on (and their false counterparts), case-insensitively.
  • Enum types restrict values and show a dropdown in Swagger UI.
  • list[str] must be wrapped in Query() to read repeated params like ?tag=veg&tag=spicy; without it FastAPI would expect a body.

When to use which

  • Path parameters identify a resource: /restaurants/{restaurant_id}/menu. If the value is missing, the URL means something else.
  • Query parameters modify the view: filtering, sorting, pagination and search, e.g. /restaurants?city=bengaluru&veg_only=true&page=2.

A good rule: if removing the value changes which resource you mean, it belongs in the path; if it only changes how you see a collection, it belongs in the query.

Common mistakes

  • Writing q: str = None. It works at runtime but is a wrong type; use q: str | None = None (or Optional[str] on older Python).
  • Forgetting that a param with no default is required even if it is a query param; clients get a 422 "Field required".
  • Putting sensitive data (tokens, OTPs) in query strings, where they end up in server logs and browser history.
  • Using a path converter for file paths: you need {file_path:path} to capture slashes.

The modern style is Annotated, e.g. limit: Annotated[int, Query(ge=1, le=100)] = 20, which keeps the default as a normal Python default and adds validation metadata.

How FastAPI classifies a parameter. The path and the type hint decide where each value is read from.
  1. Name is in the path braces: Treated as a required path parameter.
  2. Type is a Pydantic model: Read from the JSON request body.
  3. Type is a simple scalar: Read from the query string.
  4. Has a default value: Query parameter becomes optional.
  5. Explicit marker used: Query, Path, Header or Body override inference.

Code examples

Path, required query and optional query parameters

from enum import Enum
from typing import Annotated
from fastapi import FastAPI, Query

app = FastAPI()

class SortBy(str, Enum):
    rating = "rating"
    delivery_time = "delivery_time"

@app.get("/cities/{city}/restaurants")
def list_restaurants(
    city: str,                                     # path: always required
    cuisine: str,                                  # query: required (no default)
    veg_only: bool = False,                        # query: optional
    sort: SortBy = SortBy.rating,                  # query: restricted values
    q: str | None = None,                          # query: optional, may be None
    tags: Annotated[list[str], Query()] = [],      # repeated: ?tags=a&tags=b
    page: Annotated[int, Query(ge=1)] = 1,
):
    return {"city": city, "cuisine": cuisine, "veg_only": veg_only,
            "sort": sort, "q": q, "tags": tags, "page": page}

Each parameter's source is inferred from the path and its type. Query() is needed for list parameters and for adding constraints like ge=1.

Capturing a path that contains slashes

from fastapi import FastAPI

app = FastAPI()

@app.get("/files/{file_path:path}")
def read_file(file_path: str):
    # GET /files/reports/2026/q1.csv  ->  file_path = "reports/2026/q1.csv"
    return {"file_path": file_path}

The :path converter, inherited from Starlette, lets a path parameter match across slashes.

Key points

  • Name in {braces} = path parameter, always required
  • Scalar type without default = required query param; with default = optional
  • Pydantic model type = request body
  • List query params need Query(), e.g. Annotated[list[str], Query()]
  • Invalid conversions return 422 with the parameter location in loc

Common follow-up questions

  • How would you accept a list of values in a query parameter?
  • How do you add min/max validation to a query parameter?
  • When would you choose a path parameter over a query parameter in API design?
  • How do you read a header or cookie value in FastAPI?

Interview tips

  • State the classification rules in order; it shows you understand how FastAPI reads signatures
  • Give the API design rule of thumb: identity in the path, filtering and pagination in the query
  • Mention Annotated as the current recommended style

Concepts covered

path parameters, query parameters, type coercion, optional parameters, Annotated

More FastAPI Interview questions