Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 Response Model Basics📚 Pydantic Models📚 Nested Responses📚 Response Codes📚 Multiple Responses📚 List Responses📚 Response Filtering📚 Response Documentation
Fastapi/Response Models/Response Codes

Response Codes

Learn the fundamentals of response codes in FastAPI.

🎯 Core Concept

HTTP status codes communicate the outcome of an API request. Choosing the correct status code is essential for client applications to understand what happened and how to respond appropriately.

📖 What You'll Learn

In this section, you'll understand:

  • Common HTTP status codes (2xx, 3xx, 4xx, 5xx)
  • When to use specific status codes
  • Using `status_code` parameter in FastAPI
  • Conditional status codes based on logic
  • Semantic status code selection

💡 Common Status Codes

from fastapi import FastAPI, status, HTTPException

app = FastAPI()

@app.get("/items/{item_id}", status_code=status.HTTP_200_OK)
async def get_item(item_id: int):
    return {"id": item_id}

@app.post("/items", status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):
    return {"id": 1, **item.dict()}

@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_item(item_id: int):
    return None

@app.get("/items/{item_id}", status_code=status.HTTP_200_OK)
async def get_item_or_404(item_id: int):
    if item_id < 1:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Item not found"
        )
    return {"id": item_id}

Status Codes by Operation

# GET (retrieve)
@app.get("/users/{user_id}", status_code=200)  # OK

# POST (create)
@app.post("/users", status_code=201)  # Created

# PUT (replace)
@app.put("/users/{user_id}", status_code=200)  # OK

# PATCH (partial update)
@app.patch("/users/{user_id}", status_code=200)  # OK

# DELETE
@app.delete("/users/{user_id}", status_code=204)  # No Content

Dynamic Status Codes

from fastapi.responses import JSONResponse

@app.post("/items")
async def create_or_update(item: Item, db: Session = Depends(get_db)):
    existing = db.query(Item).filter_by(id=item.id).first()
    if existing:
        existing.update(**item.dict())
        return JSONResponse(
            status_code=200,
            content={"status": "updated"}
        )
    else:
        db.add(Item(**item.dict()))
        return JSONResponse(
            status_code=201,
            content={"status": "created"}
        )

🔑 Key Takeaways

  • ✅ Understand the purpose of response codes
  • ✅ Know when to apply this pattern
  • ✅ Recognize its benefits in real-world scenarios
  • ✅ Be prepared to use it in your projects

Ready to explore more? Check out the advanced section for production patterns and edge cases.


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn