HTTPException

Raising Errors

Example

Raise HTTPException to stop and return an error response:

from fastapi import FastAPI, HTTPException

app = FastAPI()
COURSES = {1: "HTML", 2: "CSS"}

@app.get("/courses/{course_id}")
def get_course(course_id: int):
    if course_id not in COURSES:
        raise HTTPException(status_code=404, detail=f"Course {course_id} not found")
    return {"id": course_id, "title": COURSES[course_id]}

Requests and responses

GET /courses/1
→ 200 {"id": 1, "title": "HTML"}
GET /courses/99
→ 404 {"detail": "Course 99 not found"}

Custom Exception Handlers

Example

Map your own exceptions to responses in one place:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

class InsufficientFunds(Exception):
    def __init__(self, needed: float):
        self.needed = needed

app = FastAPI()

@app.exception_handler(InsufficientFunds)
async def funds_handler(request: Request, exc: InsufficientFunds):
    return JSONResponse(status_code=400, content={"error": "insufficient_funds", "needed": exc.needed})

@app.post("/wallet/pay")
def pay(amount: float, balance: float = 100):
    if amount > balance:
        raise InsufficientFunds(needed=amount - balance)
    return {"paid": amount}

Requests and responses

POST /wallet/pay?amount=40
→ 200 {"paid": 40.0}
POST /wallet/pay?amount=250
→ 400 {"error": "insufficient_funds", "needed": 150.0}