tezvyn:

FastAPI: Use HTTPException to Return Client Errors

AI-drafted, machine-checkedSource: fastapi.tiangolo.comadvanced

FastAPI's HTTPException is your tool for stopping an operation and sending a clean HTTP error. Raise it when business logic fails, like a missing database record. The footgun is catching it yourself; just `raise` it and let FastAPI do the rest.

WHY IT EXISTS APIs need a standard way to tell clients when something goes wrong. Instead of returning a generic 500 Internal Server Error for everything, or manually crafting JSON error responses, FastAPI provides a dedicated exception class that integrates with its machinery to produce correct, client-friendly HTTP error responses.

THE MENTAL MODEL HTTPException is not a typical Python exception you'd catch and handle. Think of it as a special signal to the framework itself. When you raise HTTPException, you're telling FastAPI, "Stop everything for this request, and send this specific HTTP error back to the client immediately." It's a control flow mechanism for terminating a request with a known error state.

HOW IT WORKS You import HTTPException from fastapi. Inside your path operation function, when you detect an error condition (like a requested ID not found in the database), you instantiate and raise it. You must provide a status_code (like 404) and can optionally provide a JSON-serializable detail message and custom headers. FastAPI has a default exception handler that catches HTTPException, stops the code execution for that request, and generates a JSON response with the provided status, detail, and headers.

WHEN TO USE IT Use HTTPException for all expected, client-caused errors within your application logic. This includes situations like: an item not found (404), a user not having permission (403), a conflict with an existing resource (409), or any other business rule violation that you can map to a 4xx HTTP status code.

WHEN NOT TO USE IT Do not use HTTPException for errors related to request validation. FastAPI handles that automatically. If a client sends a request body that doesn't match your Pydantic model, FastAPI will automatically raise a RequestValidationError and return a 422 Unprocessable Entity response. You also shouldn't use it for unexpected server-side bugs, which should correctly result in a 500 error.

ONE CANONICAL EXAMPLE Imagine a function to fetch an item by ID from a dictionary acting as a fake database. If the item ID doesn't exist, you raise a 404. In your code, you would check if item_id not in fake_items_db:. If that condition is true, you execute raise HTTPException(status_code=404, detail="Item not found"). If a client requests a non-existent item, they receive a 404 status and a JSON body like {"detail": "Item not found"}.

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.