Skip to main content
Just as we validate and structure incoming requests, we must also control, sanitize, and format outbound data. FastAPI achieves this using Response Models and standard status code responses.

1. Outbound Data Serialization Flow

When a route function returns data, FastAPI filters the response schema, strips out disallowed properties (like hashed passwords or internal notes), serializes it to JSON, and sets the configured HTTP status code.

2. Response Models

By declaring a response_model in your path operation decorator, you tell FastAPI to:
  • Validate the output: Ensure the return data complies with the schema.
  • Serialize the data: Convert complex Python objects (like database models) into JSON.
  • Filter private data: Exclude fields not explicitly declared in the response model.

Example: Sanitizing Employee Data

Suppose our internal database contains private fields like base_salary and tax_id that we do not want to share publicly.

3. Setting HTTP Status Codes

You can configure the default success status code for a route using the status_code parameter in the decorator. It is recommended to use the constants provided in the status module for readability.

4. Raising HTTP Exceptions

When a request goes wrong (e.g., resource not found, invalid permissions), you should interrupt the flow immediately by raising an HTTPException.

5. Custom Responses

Sometimes you need to return something other than standard JSON—for example, HTML pages, static text, redirect headers, or files (like downloading an employee report PDF). You can return a custom Response directly: