0
0
FastAPIframework~8 mins

Response model exclude and include in FastAPI - Performance & Optimization

Choose your learning style9 modes available
Performance: Response model exclude and include
MEDIUM IMPACT
This affects the size of the JSON response sent to the client, impacting network load and client rendering speed.
Sending API responses with only necessary fields
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    id: int
    username: str
    email: str
    password: str

@app.get('/user', response_model=User, response_model_exclude={'password'})
async def get_user():
    user = User(id=1, username='alice', email='alice@example.com', password='secret')
    return user
Excludes password field from response, reducing payload size and improving security.
📈 Performance GainSmaller JSON response reduces network transfer and speeds up LCP.
Sending API responses with only necessary fields
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    id: int
    username: str
    email: str
    password: str

@app.get('/user', response_model=User)
async def get_user():
    user = User(id=1, username='alice', email='alice@example.com', password='secret')
    return user
Returns all fields including sensitive data like password, increasing response size and security risk.
📉 Performance CostAdds unnecessary data to response, increasing payload size and slowing LCP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Full response with all fieldsN/AN/AHigher due to larger JSON parsing[X] Bad
Response with exclude/include to limit fieldsN/AN/ALower due to smaller JSON parsing[OK] Good
Rendering Pipeline
The response model exclude/include affects the JSON serialization stage before sending data to the client. Smaller JSON means less data to parse and render on the client side.
JSON Serialization
Network Transfer
Client Rendering
⚠️ BottleneckNetwork Transfer due to payload size
Core Web Vital Affected
LCP
This affects the size of the JSON response sent to the client, impacting network load and client rendering speed.
Optimization Tips
1Always exclude sensitive or unnecessary fields to reduce response size.
2Use include to send only the fields the client needs.
3Smaller JSON responses improve network transfer and page load speed.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using response_model_exclude in FastAPI?
AAdds more fields to the response
BReduces response JSON size, improving load speed
CIncreases server CPU usage
DImproves database query speed
DevTools: Network
How to check: Open DevTools, go to Network tab, make the API request, and inspect the response payload size and content.
What to look for: Look for smaller response size and absence of unnecessary fields in JSON to confirm good performance.