FastAPI Request and Response Models: Validate Input and Limit Public Data
FastAPI lets you declare where request data comes from and what shape it has using Python type hints and Pydantic models. Path parameters come from the URL, simple types default to query parameters, and Pydantic models are read from the request body. Set a response_model to validate returned data, filter which fields are public, and include the same contract in OpenAPI documentation.
FastAPI lets you declare where request data comes from and what shape it has using Python type hints and Pydantic models. Path parameters come from the URL, simple types default to query parameters, and Pydantic models are read from the request body. Set a response_model to validate returned data, filter which fields are public, and include the same contract in OpenAPI documentation.
Understand path operations and parameter sources
A FastAPI app registers path operation decorators that connect an HTTP method and path to a function, such as @app.get('/items/{item_id}'). FastAPI inspects the function parameters and their type hints. A parameter whose name appears in the path is read from the path; singular types such as int or str are treated as query parameters by default; a Pydantic BaseModel type is treated as the request body.
Declaring a value as optional is not enough by itself. For example, q: str | None = None is optional because it has a default value. Type hints also help editors and static tools catch mistakes. Request bodies are normally used with methods such as POST, PUT, and PATCH. A GET body has undefined behavior in the specifications and may not work through intermediaries, so avoid it.
Declare an input contract with Pydantic
Define a body model as a BaseModel subclass and give its fields Python types, defaults, or Field constraints. For example, Field(gt=0) requires a price above zero, and max_length can constrain a description. These declarations connect the accepted input shape and validation rules to API documentation.
An item update can receive item_id from the path, an Item model from the body, and an optional q query value. FastAPI reads each from the right place, avoiding repeated manual extraction and conversion of raw JSON. Model validation does not replace all business rules: application logic must still check whether a record exists or whether the caller is allowed to change it.
Limit returned data with response_model
A response model defines the server’s output contract. When a path operation decorator has response_model, FastAPI validates and converts the returned value, adds its response schema to OpenAPI and the automatic docs, and filters fields that are not in the model. A response that does not match the model indicates a server-side problem and is generally treated as a response validation error.
Input and output models often need to differ. A signup request may need a password, but a public user response must not include it. Define separate models such as UserCreate and UserPublic, and declare UserPublic as the response model. This makes the public boundary explicit instead of relying on a handler not to return a secret field.
If both a return annotation and response_model are declared, response_model takes priority for FastAPI validation, documentation, and output filtering. This is useful when a function returns a database object but the public shape should be a Pydantic model. response_model_include/exclude can be a quick shortcut, but OpenAPI may still describe the complete model. Prefer a separate output model for a stable public contract.
Reuse checks with dependencies
Declare repeated work, such as looking up the current user or a database session, as a dependency. FastAPI runs it before the path operation, injects its result, and resolves sub-dependencies as a tree. Annotated can preserve type information for editors and static checking. Synchronous and asynchronous dependency functions can be mixed with sync or async path operations.
Dependency parameters and validation requirements are included in OpenAPI and the interactive docs. Declaring an authentication or authorization dependency does not by itself prove that the policy is correct: define which callers must be allowed or denied and verify protected routes accordingly.
Check the contract with a small endpoint
Separate input and output models, for example UserCreate with username and password, and UserPublic with username only. An endpoint can accept UserCreate and set response_model=UserPublic. Even if the internal returned object has extra fields, the public response is limited to the output model. A save_user call in such an example is only a placeholder, not evidence of an executed database write.
Verify in development
Check the project’s Python, FastAPI, and Pydantic versions; use model APIs supported by the installed versions.
Run the development server and call the path operation. Confirm wrong types, missing required fields, and constraint violations are rejected as expected.
Send valid input and inspect the status and JSON shape. Confirm internal fields absent from the response model are filtered.
Check /docs or the OpenAPI schema for the intended path, query, body, and response declarations.
If a dependency supplies authorization or shared state, check both an allowed request and a request that should be denied.
If behavior is wrong, inspect field types/defaults, path names, response_model, and dependency scope in order. If sensitive output appears, remove it from the public response model and verify again instead of relying on an exclusion shortcut.
FastAPI model declarations define more than input validation and docs. A response model establishes the boundary of data sent outside the service; separate input and output models make that public contract easier to control when internal data changes.
References
[FastAPI: First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/)
[FastAPI: Request Body](https://fastapi.tiangolo.com/tutorial/body/)
[FastAPI: Response Model](https://fastapi.tiangolo.com/tutorial/response-model/)
[FastAPI: Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/)
[FastAPI: Body - Fields](https://fastapi.tiangolo.com/tutorial/body-fields/)