📖 Scenario: You are building a simple API to share information about books. You want to make sure the API only sends back the right details about each book to users.
🎯 Goal: Create a FastAPI app that defines a response model using pydantic. The API should return book data with only the specified fields.
📋 What You'll Learn
Create a Book model using pydantic.BaseModel with fields title (string) and author (string).
Create a FastAPI app instance called app.
Create a GET endpoint /book that returns a Book instance.
Use the response_model parameter in the route decorator to declare the response model.
💡 Why This Matters
🌍 Real World
APIs often need to send back data in a clear, consistent format. Response models help define exactly what data clients receive.
💼 Career
Knowing how to declare response models in FastAPI is essential for backend developers building reliable and maintainable APIs.
Progress0 / 4 steps
1
Create the Book model
Create a Book class that inherits from pydantic.BaseModel. It should have two string fields: title and author.
FastAPI
Hint
Use class Book(BaseModel): and define title and author as string fields.
2
Create the FastAPI app
Import FastAPI and create an app instance called app.
FastAPI
Hint
Use app = FastAPI() to create the app instance.
3
Create the GET endpoint with response model
Create a GET endpoint /book using @app.get. Use the response_model=Book parameter. The endpoint should return a Book instance with title set to 'The Great Gatsby' and author set to 'F. Scott Fitzgerald'.
FastAPI
Hint
Use @app.get("/book", response_model=Book) and return a Book instance with the given title and author.
4
Complete the FastAPI app
Make sure the full code includes the Book model, the app instance, and the GET endpoint /book with the response model declared.
FastAPI
Hint
Check that all parts are included: model, app, and endpoint with response model.
Practice
(1/5)
1. What is the main purpose of declaring a response_model in a FastAPI route?
easy
A. To handle incoming request validation
B. To define the shape and type of data the API sends back to the client
C. To set the HTTP status code for the response
D. To specify the database model used for storing data
Solution
Step 1: Understand response_model role
The response_model tells FastAPI what data shape to send back, ensuring output matches a defined structure.
Step 2: Differentiate from other parameters
It does not set status codes, validate requests, or define database models, which are separate concerns.
Final Answer:
To define the shape and type of data the API sends back to the client -> Option B
Quick Check:
response_model defines output data shape = D [OK]
Hint: Response model controls output data shape, not input or status [OK]
Common Mistakes:
Confusing response_model with request body validation
Thinking response_model sets HTTP status codes
Assuming response_model defines database schema
2. Which of the following is the correct way to declare a response model in a FastAPI route?
easy
A. @app.get('/items', model_response=Item)
B. @app.get('/items', response=Item)
C. @app.get('/items', responseModel=Item)
D. @app.get('/items', response_model=Item)
Solution
Step 1: Recall FastAPI syntax for response model
The correct parameter name is response_model in the route decorator.
Step 2: Check each option
Only @app.get('/items', response_model=Item) uses the exact correct syntax response_model=Item. Others use incorrect parameter names.
Final Answer:
@app.get('/items', response_model=Item) -> Option D
Quick Check:
Correct parameter name is response_model = C [OK]
Hint: Use exact parameter name 'response_model' in route decorator [OK]
Common Mistakes:
Using wrong parameter names like response or model_response
Capitalizing parameter names incorrectly
Omitting the response_model parameter
3. Given this FastAPI code snippet, what will be the output JSON when calling /user/1?
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
id: int
name: str
password: str
@app.get('/user/{user_id}', response_model=User)
def get_user(user_id: int):
return {"id": user_id, "name": "Alice", "password": "secret", "token": "abc123"}
medium
A. {"id": 1, "name": "Alice"}
B. {"id": 1, "name": "Alice", "password": "secret", "token": "abc123"}
C. {"id": 1, "name": "Alice", "password": "secret"}
D. Runtime error due to extra field
Solution
Step 1: Understand response_model filtering
The response_model=User tells FastAPI to return only fields defined in User model, ignoring extra fields like token.
Step 2: Analyze returned dictionary
The returned dict has id, name, password, and extra token. The extra token is removed in output.
Final Answer:
{"id": 1, "name": "Alice", "password": "secret"} -> Option C
Quick Check:
response_model filters extra fields = A [OK]
Hint: Response model hides fields not declared in model [OK]
Common Mistakes:
Expecting extra fields to appear in output
Thinking extra fields cause errors
Confusing input validation with output filtering
4. Identify the error in this FastAPI route declaration: