Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 Error Basics📚 HTTP Exceptions📚 Custom Exceptions📚 Error Responses📚 Exception Handlers📚 Validation Errors📚 Error Logging📚 Error Best Practices
Fastapi/Error Handling/Http Exceptions

HTTP Exceptions

FastAPI provides HTTPException for returning HTTP errors with proper status codes and messages. It's the standard way to signal client errors in your API.

🎯 How HTTPException Works

HTTPException raises an error that FastAPI automatically converts to an HTTP response:

from fastapi import FastAPI, HTTPException
from fastapi import status

app = FastAPI()

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

📖 Basic Usage

# 400 Bad Request - Invalid input
raise HTTPException(status_code=400, detail="Invalid input data")

# 401 Unauthorized - Authentication required
raise HTTPException(status_code=401, detail="Not authenticated")

# 403 Forbidden - No permission
raise HTTPException(status_code=403, detail="No access to this resource")

# 404 Not Found - Resource doesn't exist
raise HTTPException(status_code=404, detail="Resource not found")

# 409 Conflict - Resource conflict
raise HTTPException(status_code=409, detail="Resource already exists")

💡 Adding Context to Errors

from fastapi import status

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    if user_id < 0:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail="User ID must be positive",
            headers={"X-Error-Code": "INVALID_USER_ID"}
        )
    return {"user_id": user_id}

🔍 With Authentication Headers

@app.get("/secure")
async def secure_endpoint(token: str = None):
    if not token:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Authentication required",
            headers={"WWW-Authenticate": "Bearer"}
        )
    return {"message": "authenticated"}

How it applies to real-world API development

In production APIs, HTTPException is used for:

  • Resource not found scenarios (404)
  • Authentication failures (401)
  • Permission denied cases (403)
  • Input validation failures (400)
  • Business logic violations (409, 422)

Example: E-commerce API

@app.post("/orders/")
async def create_order(order: Order, current_user: User):
    if not current_user.is_verified:
        raise HTTPException(
            status_code=403,
            detail="Email must be verified to place orders"
        )

    if order.total < 0:
        raise HTTPException(
            status_code=400,
            detail="Order total cannot be negative"
        )

    return {"order_id": 123, "status": "created"}

Common patterns and best practices

  • ✅ Use HTTPException for expected errors
  • ✅ Use appropriate status codes
  • ✅ Provide clear, actionable error messages
  • ✅ Don't expose internal implementation details
  • ✅ Add headers when needed (e.g., WWW-Authenticate)
  • ✅ Log exceptions for debugging
  • ✅ Test error scenarios
  • ✅ Return consistent error formats

🔑 Key Takeaways

  • ✅ HTTPException converts Python errors to HTTP responses
  • ✅ Use status constants from fastapi.status module
  • ✅ Provide meaningful detail messages
  • ✅ Map errors to appropriate HTTP status codes
  • ✅ HTTPException is the FastAPI way of error handling

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