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/Client Errors

Client Error Codes (4xx) ❌

Client error codes indicate that the request was invalid or couldn't be processed. They range from 400-499.

Common Client Error Codes

400 Bad Request

The request is malformed or invalid.

from fastapi import HTTPException

@app.get("/items")
async def list_items(limit: int):
    if limit < 1:
        raise HTTPException(status_code=400, detail="limit must be at least 1")
    return {"items": []}

401 Unauthorized

Authentication is required but not provided.

from fastapi.security import HTTPBearer

security = HTTPBearer()

@app.get("/protected")
async def protected_route(credentials = Depends(security)):
    if not credentials:
        raise HTTPException(status_code=401, detail="Not authenticated")
    return {"data": "secret"}

403 Forbidden

Authenticated, but not allowed to access.

@app.delete("/admin/users/{user_id}")
async def delete_user(user_id: int, current_user = Depends(get_current_user)):
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not authorized")
    return {"deleted": True}

404 Not Found

Resource doesn't exist.

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    user = db.get_user(user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user

422 Unprocessable Entity

Request is valid but contains semantic errors.

# FastAPI automatically returns 422 for:
# - Type validation errors
# - Missing required fields
# - Invalid format

@app.post("/users")
async def create_user(name: str, age: int):
    # POST {"name": "John", "age": "invalid"} → 422
    # POST {"name": "John"} → 422 (age required)
    return {"id": 1, "name": name, "age": age}

Error Code Comparison

CodeMeaningExample
400Bad RequestInvalid query parameters
401UnauthorizedMissing API key
403ForbiddenNo permission
404Not FoundResource doesn't exist
422Unprocessable EntityInvalid field types

Returning Client Errors

from fastapi import HTTPException, status

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    item = db.get_item(item_id)

    if not item:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Item not found"
        )

    return item

🔑 Key Takeaways

  • ✅ 400 = Bad Request (client error)
  • ✅ 401 = Unauthorized (not authenticated)
  • ✅ 403 = Forbidden (no permission)
  • ✅ 404 = Not Found (doesn't exist)
  • ✅ 422 = Validation Error (invalid data)
  • ✅ Use HTTPException to return errors
  • ✅ Include helpful error messages

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