Guides › Validation and Auto-Docs: Guarding Endpoints with FastAPI

Lesson 7 of 8 2 min read All lessons

Validation and Auto-Docs: Guarding Endpoints with FastAPI

When you build a public API, users will send invalid data: negative numbers, letters where numbers belong, or page sizes of ten million. Rather than writing dozens of manual if statements, FastAPI lets you declare validation rules right in your route parameters.

Think of validation as the security guard at an office turnstile. If an employee tries to swipe a badge that is expired or missing credentials, the turnstile stays locked and the guard politely explains the issue right at the entrance (HTTP 422 Unprocessable Entity). Bad data never enters the building or touches your database.

How validation works in FastAPI

Import Query and Path from fastapi to attach constraints like minimum value (ge), maximum value (le), or regex patterns:

from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items")
def get_items(limit: int = Query(10, ge=1, le=50)):
    return {"limit": limit}

Test validation three ways

1. In your browser

Visit https://api.computewithpour.com/v1/names?limit=51 in your browser. Notice the server returns 422 with a structured error stating that the value must be less than or equal to 50.

2. With curl

Call the endpoint with curl to see the exact 422 status code and error schema:

curl -i "https://api.computewithpour.com/v1/names?limit=51"

3. With Python

Check how a Python client catches the 422 error:

import requests

r = requests.get("https://api.computewithpour.com/v1/names", params={"limit": 51})
print("Status:", r.status_code)  # 422
print("Error detail:", r.json()["detail"][0]["msg"])

Try it in the API Lab and /docs

In the API Lab, send /v1/names?limit=0 and watch the validation error appear. Then visit our /docs page. Look at the description for limit: FastAPI automatically documented the allowable range (1 to 50) straight from the Python code.

What to notice

You never have to maintain separate documentation that drifts out of date. The moment you declare Query(10, ge=1, le=50), FastAPI does two things at once: it blocks invalid requests with HTTP 422, and it updates /docs and /openapi.json automatically.

Deepen your Python vocabulary

Writing declarative code with FastAPI relies heavily on Python's type system, default arguments, and exception handling. To gain full command over every Python keyword and syntax convention, consult 35 PY Keys in our library.

Challenge

Add validation to a /names route so limit must be between 1 and 5 (default 3) and offset must be ≥ 0. Verify that limit=6 is rejected with status 422.

Show the answer

Use Query(3, ge=1, le=5) and Query(0, ge=0). When a caller passes limit=6, FastAPI rejects the request with HTTP 422 before the function body executes.

from fastapi import FastAPI, Query
from starlette.testclient import TestClient

app = FastAPI()
NAMES = [{"id": 1, "name": "Ada"}, {"id": 2, "name": "Grace"}, {"id": 3, "name": "Linus"}]


@app.get("/names")
def get_names(limit: int = Query(3, ge=1, le=5), offset: int = Query(0, ge=0)):
    return NAMES[offset : offset + limit]


client = TestClient(app)
assert client.get("/names?limit=2").status_code == 200
assert client.get("/names?limit=6").status_code == 422
print("All validation tests passed!")