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 BaseModel

class ItemResponse(BaseModel):
name: str
price: float

Using Response Model in FastAPI

from fastapi import FastAPI

app = 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: str
price: float

class ItemResponse(BaseModel):
name: str

@app.post("/items/", response_model=ItemResponse)
def create_item(item: Item):
return item

Input includes price, but response hides it.

Best Practices

1. Always use response models
2. Separate request & response schemas
3. Use correct status codes
4. Never expose sensitive data

Common Mistakes

1. Returning raw database objects
2. Not using response_model
3. Using wrong status codes
4. Exposing confidential fields (passwords, tokens)

Key Takeaways

  • Response models control output structure
  • FastAPI filters unwanted fields automatically
  • Status codes improve API communication
  • HTTPException is used for error handling

Comments

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Middleware & CORS in FastAPI

Python Data Handling