Response Models & Status Codes in FastAPI
We focused on handling incoming data.Now it’s time to control what your API sends back to the client.
A professional API should:
- Return clean and structured responses
- Use proper status codes
- Hide unnecessary data
FastAPI makes this super easy using Response Models.
What is a Response Model?
A response model defines the structure of the data your API returns.It ensures:
- Only required fields are returned
- Data is validated before sending
- Sensitive data is hidden
Creating a Response Model
from pydantic import BaseModelclass ItemResponse(BaseModel):name: strprice: float
Using Response Model in FastAPI
from fastapi import FastAPIapp = FastAPI()@app.get("/item/", response_model=ItemResponse)def get_item():return {"name": "Laptop","price": 50000,"secret": "hidden data"}
Output:
{"name": "Laptop","price": 50000}
secret field is automatically removed!
Why Use Response Models?
- Prevent exposing sensitive data
- Maintain consistent API structure
- Improve documentation
- Add validation to responses
HTTP Status Codes
Status codes tell the client what happened.
Common Status Codes:
| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 404 | Not Found |
| 500 | Server Error |
Setting Status Codes
from fastapi import status@app.post("/items/", status_code=status.HTTP_201_CREATED)def create_item():return {"message": "Item created"}
Handling Errors
Use HTTPException for errors:
from fastapi import HTTPException@app.get("/items/{item_id}")def get_item(item_id: int):if item_id != 1:raise HTTPException(status_code=404, detail="Item not found")return {"item_id": item_id}
Custom Response Example
@app.get("/success")def success():return {"status": "success","data": {"message": "Operation completed"}}Combining Request & Response Models
class Item(BaseModel):name: strprice: floatclass ItemResponse(BaseModel):name: str@app.post("/items/", response_model=ItemResponse)def create_item(item: Item):return itemInput includes
price, but response hides it.Best Practices
1. Always use response models2. Separate request & response schemas3. Use correct status codes4. Never expose sensitive dataCommon Mistakes
1. Returning raw database objects2. Not usingresponse_model3. Using wrong status codes4. Exposing confidential fields (passwords, tokens)Key Takeaways
- Response models control output structure
- FastAPI filters unwanted fields automatically
- Status codes improve API communication
HTTPExceptionis used for error handling
Comments
Post a Comment