VOOZH about

URL: https://www.geeksforgeeks.org/python/fastapi-response-model/

⇱ FastAPI - Response Model - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

FastAPI - Response Model

Last Updated : 11 May, 2026

The response_model acts as a security gate and a data formatter between the internal logic (database, raw data) and the outside logic. Its main features are:

  • Data Filtering: removes extra fields returned by your database automatically, that shouldn't be public.
  • Type Conversion: Automatically converts data types (e.g., a UUID object or a Datetime object becomes a standard string in the JSON).
  • Documentation: Your models are automatically reflected in the /docs (Swagger UI), creating a clear contract for frontend developers.
  • Validation: If the returned data does not match the defined model (for example, None instead of a string), FastAPI raises a server error instead of returning invalid data to the client.

Without a response model, an API may expose sensitive data such as hashed passwords, internal IDs, or timestamps. Defining a response model restricts the output to specified fields, ensuring only intended data is returned to the client.

Implementation Guide

1. Define Your Schemas: It is a better practice to separate your Input model (what the user sends) from your Output model (what the user sees).

2. Apply the response_model: You apply the model in the path operation decorator, not in the function signature.

Input:

👁 fast_api_requestmodel
Request

Output:

👁 fast_api_requestmodel2
Response

Advanced Control: Filtering Defaults

We can hide fields that haven't been changed or are empty (if required) by using the following decorator parameters:

ParameterEffect
response_model_exclude_unsetOnly includes fields that were actually set in the code.
response_model_exclude_noneRemoves any field with a null value from the final JSON.
Comment