Skip to main content
Just as you validate and structure incoming requests, you must also control, sanitise, and format the data your API sends back. Returning raw internal data — with database IDs, hashed passwords, salary figures, or internal flags — is a common security mistake. FastAPI’s response_model parameter gives you a clean, declarative way to filter exactly what leaves your server, while HTTPException lets you abort with precise error responses at any point. This lesson covers both, plus custom response classes for those times when JSON isn’t what the client needs.

Outbound Data Serialization Flow

When a route function returns data, FastAPI filters it against the response schema, strips out any fields not declared in that schema, serialises the allowed fields to JSON, and sets the configured HTTP status code.

Response Models

By declaring a response_model in your path operation decorator, you tell FastAPI to:
  1. Validate the output — ensure the return data conforms to the schema.
  2. Serialize the data — convert complex Python objects (like database models) into JSON.
  3. Filter private data — exclude any fields not declared in the response model.

Example: Sanitising Employee Data

Suppose your internal data contains private fields like base_salary and tax_id that you never want to expose to clients:
The client receives only:
The base_salary and tax_id fields are never included in the response, regardless of what the function returns internally.
Without a response_model, FastAPI returns everything your function returns. Always declare a response_model for endpoints that touch internal or sensitive data.

Setting HTTP Status Codes

You can configure the default success status code for a route using the status_code parameter. Use the status module constants for readability and maintainability:
Always use status.HTTP_201_CREATED instead of the raw integer 201. It’s self-documenting and IDE-friendly — your editor will auto-complete the constant name and catch typos.

Raising HTTP Exceptions

When something goes wrong — a resource isn’t found, the caller lacks permission, a business rule is violated — raise an HTTPException to halt execution immediately and return a clear error response:
The client receives:

Common Exception Patterns


Response Model Options

FastAPI provides extra parameters on response_model to fine-tune the output:

Custom Response Classes

Sometimes JSON isn’t the right format — you might need to return HTML, plain text, a file download, or a redirect. FastAPI supports this with response classes:
For JSON APIs, you rarely need to return a custom response class directly — FastAPI handles JSON serialisation for you. Custom response classes are most useful for file downloads, HTML rendering, and redirects.

Complete Example: Create and Retrieve with Filtering