Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 HTTP Status Codes📚 2xx Success Codes📚 4xx Client Errors📚 5xx Server Errors📚 Returning Status Codes📚 Custom Status Codes📚 Status Code Best Practices
Fastapi/Status Codes/Returning Status

Returning Status Codes 🎯

Explicitly setting status codes in your responses tells clients exactly what happened.

Using Status Code Parameter

from fastapi import status

@app.post("/items", status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):
    return db.create(item)

Different Methods, Different Codes

# GET returns 200
@app.get("/items/{item_id}")
async def get_item(item_id: int):
    return item

# POST returns 201
@app.post("/items", status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):
    return item

# PUT returns 200
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    return item

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

Using HTTPException

from fastapi import HTTPException

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    item = db.get(item_id)
    if not item:
        raise HTTPException(
            status_code=404,
            detail="Item not found"
        )
    return item

🔑 Key Takeaways

  • ✅ Use status_code parameter for endpoints
  • ✅ Use HTTPException for errors
  • ✅ Include detail messages
  • ✅ Different methods use different codes

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