- Courses
- 📚Libraries & Frameworks
- ⚡FastAPI
- Foundations of FastAPI
- Basic Routing
- Type Validation and Automatic Documentation
On this page
How FastAPI Validates Input and Documents Itself
Published on August 9, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
A type hint on a FastAPI path operation function does two things at once: it tells FastAPI how to validate the value coming in, and it becomes part of the schema used to generate that endpoint's entry in the interactive documentation. Both behaviors come from the exact same source — the type hint itself — which is why writing x: int is the entire implementation needed for both rejecting x=three with a structured error and showing x as an integer field in the docs, with no separate validation code and no separate documentation file written by hand.
Type Hints as Validation Rules​
FastAPI is built on Starlette for the web layer and Pydantic for data validation, and Pydantic is what actually performs the conversion and checking behind a type hint like int, str, or bool. Declaring a parameter's type isn't a hint in the loose sense of a comment — it's an instruction Pydantic enforces on every request before the path operation function runs at all.
from fastapi import FastAPI
app = FastAPI()
@app.get("/add")
def add(x: int, y: int):
return {"sum": x + y}
/add?x=3&y=4 converts both query values to integers and returns {"sum": 7}. /add?x=three&y=4 fails that conversion for x, and the function body never executes — FastAPI responds with a 422 Unprocessable Entity status before add is ever called.
What a Validation Error Actually Looks Like​
The body of that 422 response is structured, not just a plain error string, and reading it correctly means knowing what each field represents:
{
"detail": [
{
"type": "int_parsing",
"loc": ["query", "x"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "three",
"url": "https://errors.pydantic.dev/2.5/v/int_parsing"
}
]
}
detail is always a list, since a single request can fail validation on more than one field at once. loc gives the exact location of the problem — here, the x query parameter specifically, not just "something in the request" — which lets a client pinpoint the failing field without guessing. msg is a human-readable description of what went wrong, type is a stable, machine-readable error code (int_parsing here) that code can check against without parsing the message text, and input echoes back the exact value that was rejected, which is often the fastest way to spot a typo or an unexpected format. The url field links to Pydantic's own documentation for that specific error type, with further detail on why it occurred and how to avoid it.
Path Parameters Are Validated the Same Way​
The same underlying mechanism handles path parameters, not a separate one:
@app.get("/square/{number}")
def square(number: int):
return {"result": number ** 2}
/square/5 returns {"result": 25}. /square/five produces the same kind of 422 response shown above, just with "loc": ["path", "number"] instead of "query" — the location in the error reflects where the value came from, while the validation logic itself doesn't change based on whether the input arrived through the path or the query string.
Defaults Make Parameters Optional​
@app.get("/greet")
def greet(name: str = "Guest"):
return {"message": f"Hello, {name}!"}
/greet?name=Enrico returns {"message": "Hello, Enrico!"}. /greet, with no query string at all, returns {"message": "Hello, Guest!"} — the default value fills in for a missing parameter rather than triggering a validation error, since a missing optional parameter and an invalid one are treated as two different situations.
How the Interactive Docs Are Generated​
Every route registered on a FastAPI app contributes to a single OpenAPI schema, built automatically from each path operation's route, parameters, and type hints. That one schema is what powers both documentation interfaces available by default — they're two different presentations of the same underlying data, not two separately maintained documents.
Swagger UI (/docs)​
Visiting http://127.0.0.1:8000/docs opens Swagger UI, which lists every registered endpoint and lets each one be expanded to see its parameters, expected types, and example values. The part that makes it more than a reference page is the "Try it out" button on each endpoint: it turns the documentation into a live form, where filling in values and executing the request sends a real HTTP call to the running server and displays the actual response — including a real 422 and its full error body, if the input entered doesn't pass validation.
ReDoc (/redoc)​
Visiting http://127.0.0.1:8000/redoc opens ReDoc instead, built from that same OpenAPI schema but laid out for reading rather than for testing. A sidebar lists every endpoint, and selecting one shows detailed parameter descriptions and response schemas without an interactive form — better suited to studying an API's full surface in order than to testing one specific call.
Combining Path and Query Parameters​
@app.get("/profile/{user_id}")
def get_profile(user_id: int, show_email: bool = False):
return {
"user_id": user_id,
"email": "[email protected]" if show_email else "hidden",
}
/profile/42 returns {"user_id": 42, "email": "hidden"}. /profile/42?show_email=true returns {"user_id": 42, "email": "[email protected]"}. Both user_id and show_email appear in /docs with their correct types the moment the app starts — nothing needs to be run or tested first for the documentation to reflect them accurately, since it's generated from the same source code as the validation itself.
Practice: Extending the Pattern​
Applying the same rules to three new cases:
import math
@app.get("/sqrt/{value}")
def square_root(value: float):
return {"value": value, "result": math.sqrt(value)}
@app.get("/feature")
def feature_toggle(enabled: bool = False):
return {"feature_enabled": enabled}
@app.get("/announce")
def announce(text: str, priority: int = 1):
return {"message": f"[Priority {priority}] {text}"}
/sqrt/16 returns {"value": 16.0, "result": 4.0}, with the path parameter converted to float rather than int — /sqrt/16.5 works correctly here, where it would have failed against an int type hint. /feature?enabled=yes and /feature?enabled=1 both return {"feature_enabled": true}, since both are among the string values Pydantic recognizes as True. /announce?text=Deploy+complete&priority=2 returns {"message": "[Priority 2] Deploy complete"}, combining a required str query parameter with an optional int one in a single formatted response. Visiting /docs after adding all three shows each one listed with its correct parameter types, and sending an invalid value through the "Try it out" button — /sqrt/abc, for instance — reproduces the same structured 422 response covered earlier, without needing curl or a separate HTTP client to see it.
Key Takeaways​
A type hint on a FastAPI parameter is read once and used twice: to validate and convert the incoming value, and to describe that parameter in the OpenAPI schema that both Swagger UI and ReDoc are generated from. A validation failure returns a structured 422 response with a loc pinpointing the exact field, a type that's stable enough to check programmatically, and a msg meant for a human reading it — the same shape regardless of whether the failing value came from a path parameter, a query parameter, or a request body. Because the documentation and the validation logic are generated from the same source, there's no separate step to keep them in sync — adding a new typed parameter to a route makes it appear correctly in /docs and /redoc immediately, with no additional documentation written by hand.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Dynamic Routing and Query Parameters
Next
Pydantic Models
-
Type Hints as Validation Rules
-
What a Validation Error Actually Looks Like
-
Path Parameters Are Validated the Same Way
-
Defaults Make Parameters Optional
-
How the Interactive Docs Are Generated
- Swagger UI (/docs)
- ReDoc (/redoc)
-
Combining Path and Query Parameters
-
Practice: Extending the Pattern
-
Key Takeaways
