0
0
FastAPIframework~5 mins

Query parameter validation in FastAPI

Choose your learning style9 modes available
Introduction

Query parameter validation helps check user inputs in the URL to keep your app safe and working well.

When you want to make sure a number in the URL is within a certain range.
When you need to require a specific text value from the user in the URL.
When you want to provide default values but still check if the user input is valid.
When you want to reject requests that have wrong or missing query parameters.
When you want to give clear error messages if the user sends bad data.
Syntax
FastAPI
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/items/")
async def read_items(q: str = Query(..., min_length=3, max_length=10)):
    return {"q": q}

Use Query() to add validation rules to query parameters.

The ... means the parameter is required.

Examples
This example shows an optional query parameter q with length limits.
FastAPI
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/search/")
async def search_items(q: str = Query(None, min_length=3, max_length=20)):
    return {"query": q}
This example requires an integer num between 1 and 100.
FastAPI
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/numbers/")
async def get_numbers(num: int = Query(..., ge=1, le=100)):
    return {"number": num}
This example uses a default value but still checks minimum length.
FastAPI
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/items/")
async def read_items(q: str = Query("default", min_length=2)):
    return {"q": q}
Sample Program

This FastAPI app has a route /products/ that requires a category query parameter with length between 3 and 15 characters. It also has an optional limit parameter that must be between 1 and 50, defaulting to 10.

FastAPI
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/products/")
async def get_products(
    category: str = Query(..., min_length=3, max_length=15),
    limit: int = Query(10, ge=1, le=50)
):
    return {"category": category, "limit": limit}
OutputSuccess
Important Notes

Validation errors automatically return clear messages to the user.

You can combine many validation rules like min_length, max_length, ge (greater or equal), and le (less or equal).

Use Query(...) to make a parameter required, or Query(default_value) to make it optional.

Summary

Query parameter validation checks user inputs in the URL to keep your app safe and correct.

FastAPI uses Query() to add rules like length or number ranges.

Validation helps give clear errors and avoid bad data in your app.