FastAPI Day 2: Turning Type Hints into Automatic Path and Query Parameter Validation

This tutorial explains how FastAPI uses Python type hints together with Path() and Query() to automatically extract, type‑convert, and validate both path and query parameters, generating OpenAPI docs and standard 422 errors without manual parsing.

Tech Ocean
Tech Ocean
Tech Ocean
FastAPI Day 2: Turning Type Hints into Automatic Path and Query Parameter Validation

When building APIs, the two most common inputs are IDs embedded in the URL path and query‑string conditions; FastAPI’s handling of both is highlighted as a key advantage.

1. Path parameters

The basic usage shows a route with @app.get("/items/{item_id}") and a function def get_item(item_id: int):. The {item_id} placeholder is part of the URL, while item_id: int is a Python type annotation. FastAPI automatically:

extracts the value from the URL path,

converts it to an integer,

returns a 422 validation error if a non‑numeric value such as "abc" is supplied.

No regular expressions or manual parsing with request.args.get are required.

2. Validation rules directly on parameters

The tools Path() and Query() let you attach validation constraints. Example:

from fastapi import Path, Query

@app.get("/items/{item_id}")
def get_item(item_id: Annotated[int, Path(gt=0, description="商品ID")]):
    ...
gt=0

means the value must be greater than zero, preventing negative or zero IDs.

For pagination, you can declare:

@app.get("/items")
def list_items(
    skip: Annotated[int, Query(ge=0)] = 0,
    limit: Annotated[int, Query(ge=1, le=100)] = 10,
):
    ...
ge

stands for “greater than or equal”, and le for “less than or equal”; thus skip cannot be negative and limit is capped at 100.

Key points about these parameters

gt / ge : greater than / greater than or equal

lt / le : less than / less than or equal

min_length / max_length : string length limits

description : appears automatically in the generated /docs UI

Practical example: a user‑profile endpoint GET /users/{user_id}/profile with user_id: Annotated[int, Path(ge=1)] ensures the ID is a positive integer, and the constraint is visible in the API docs before the front‑end makes a request.

3. Query parameters: pagination and filtering

Path parameters handle variables in the URL path, while query parameters handle the part after ?. The following function demonstrates a full list endpoint with optional pagination, category filtering, sorting, and ordering:

@app.get("/items")
def list_items(
    skip: int = 0,
    limit: int = 10,
    category: str | None = None,
    sort_by: str | None = None,
    order: str = "asc",
):
    filtered = ITEMS if category is None else [i for i in ITEMS if i["category"] == category]
    if sort_by:
        filtered = sorted(filtered, key=lambda x: x[sort_by], reverse=(order == "desc"))
    return {
        "total": len(filtered),
        "skip": skip,
        "limit": limit,
        "items": filtered[skip : skip + limit],
    }

Important observations:

Optional parameters can have default values, e.g., skip: int = 0.

Using str | None lets FastAPI treat omitted values and explicit null uniformly.

Each query parameter is independent; adding new ones does not require changes to the path definition.

Validation constraints such as Query(ge=0) and Query(le=100) work for query parameters exactly as they do for path parameters.

4. How type‑annotation drives the process

FastAPI relies on Pydantic’s field validation. The flow is:

Python type annotation → Pydantic field definition → JSON Schema → OpenAPI documentation.

This chain is automatic; no extra configuration is needed.

Benefits of a single parameter declaration include runtime type validation, auto‑generated /docs parameter descriptions, and standardized 422 error responses.

5. What was done on Day 2

Implemented a path‑parameter endpoint GET /items/{item_id} with gt=0 validation.

Created a paginated list endpoint GET /items supporting skip, limit, category, sort_by, and order.

Built a user‑profile endpoint GET /users/{user_id}/profile with ge=1 constraint.

Verified all parameter validations with ten test cases.

6. Next steps

Day 3 will cover request bodies: when parameters become a full JSON structure, FastAPI uses Pydantic models to handle validation.

Related links

Official FastAPI documentation (Chinese):

https://fastapi.tiangolo.com/zh/tutorial/path-params/
https://fastapi.tiangolo.com/zh/tutorial/query-params/
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonvalidationfastapiapi-developmentpydanticquery-parameterspath-parameters
Tech Ocean
Written by

Tech Ocean

Focused on AI programming, sharing ready-to-use development efficiency solutions.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.