DEV Community

Cover image for FastAPI's Docs Raise HTTPException in the Path Function. Your Use Case Shouldn't
Gabriel Anhaia
Gabriel Anhaia

Posted on Edited on AI-assisted

FastAPI's Docs Raise HTTPException in the Path Function. Your Use Case Shouldn't


grep -rn HTTPException app/services/ is a short command with an awkward answer in a lot of FastAPI codebases that have been alive for a while: every hit is a file that holds business rules and still decides HTTP status codes.

Starlette, the toolkit FastAPI is built on, has a one-line rule about this in its exceptions docs: "You should only raise HTTPException inside routing or endpoints." FastAPI's own error-handling tutorial follows it. Its first example raises HTTPException(status_code=404, detail="Item not found") straight inside the path operation function, which is exactly where it belongs.

The trouble starts further down the same page, and it is not the docs' fault. My take: HTTPException is a fine tool for the edge of your app and a bad habit everywhere else, and coding agents are turning the bad habit into the house style.

How the leak starts

The same tutorial page notes that if you raise HTTPException from "a utility function that you are calling inside of your path operation function", FastAPI still terminates the request and sends the error to the client. That is true, and for HTTP-layer helpers (a dependency that checks a bearer token, a helper that parses a header) it is the right call.

Read quickly, though, the sentence becomes "you can raise it anywhere". So the order service, the one that holds your actual business rules, ends up looking like this:

# app/services/orders.py  (before)
from fastapi import HTTPException

from app.domain.orders import Order, OrderRepository

def cancel_order(repo: OrderRepository, order_id: str) -> Order:
    order = repo.get(order_id)
    if order is None:
        raise HTTPException(404, detail="Order not found")
    if order.status == "shipped":
        raise HTTPException(409, detail="Already shipped")
    order.status = "cancelled"
    repo.save(order)
    return order
Enter fullscreen mode Exit fullscreen mode

Nothing here is broken. The endpoint returns a 404 or a 409, the client is happy, the PR gets approved. The cost shows up the first time something other than an HTTP request calls cancel_order.

Three callers that don't speak HTTP

A Typer command that lets support staff cancel an order from a terminal. A queue worker that cancels orders when a payment fails. A plain pytest test that wants to check the shipped-order rule. None of them has a response to send, and all of them now catch an exception whose most important field is status_code.

The CLI has to translate 409 back into "this order already shipped". The worker has to decide whether a 404 means retry or give up, by reading an HTTP status. The test ends up asserting on a status code, which is an HTTP contract, inside what should be a test of a business rule:

# tests/test_orders.py  (before)
import pytest
from fastapi import HTTPException

from app.services.orders import cancel_order

def test_cannot_cancel_shipped(shipped_order_repo):
    with pytest.raises(HTTPException) as err:
        cancel_order(shipped_order_repo, "o-1")
    assert err.value.status_code == 409
Enter fullscreen mode Exit fullscreen mode

And app/services/orders.py now imports fastapi. Your core depends on your web framework, so every tool that touches the core pulls the web framework along with it.

A small orange business-rules core with HTTP cables leaking out of it toward a terminal, a worker gear and a test flask
When the core raises HTTP errors, every caller has to speak HTTP.

The fix: domain errors in, one handler out

Name the refusals in the language of the domain. They are plain Python exceptions with no import from FastAPI:

# app/domain/errors.py
class DomainError(Exception):
    """Base for every rule the core can refuse."""

class OrderNotFound(DomainError):
    def __init__(self, order_id: str) -> None:
        super().__init__(f"order {order_id} not found")
        self.order_id = order_id

class OrderAlreadyShipped(DomainError):
    def __init__(self, order_id: str) -> None:
        super().__init__(f"order {order_id} already shipped")
        self.order_id = order_id
Enter fullscreen mode Exit fullscreen mode

The service change is a two-line diff plus the import:

-from fastapi import HTTPException
+from app.domain.errors import OrderAlreadyShipped, OrderNotFound
 from app.domain.orders import Order, OrderRepository

 def cancel_order(repo: OrderRepository, order_id: str) -> Order:
     order = repo.get(order_id)
     if order is None:
-        raise HTTPException(404, detail="Order not found")
+        raise OrderNotFound(order_id)
     if order.status == "shipped":
-        raise HTTPException(409, detail="Already shipped")
+        raise OrderAlreadyShipped(order_id)
Enter fullscreen mode Exit fullscreen mode

Then the HTTP adapter gets the only map from domain errors to status codes in the whole app. FastAPI's @app.exception_handler() is the documented way to register it:

# app/http/errors.py
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

from app.domain.errors import (
    DomainError,
    OrderAlreadyShipped,
    OrderNotFound,
)

STATUS: dict[type[DomainError], int] = {
    OrderNotFound: 404,
    OrderAlreadyShipped: 409,
}

def status_for(exc: DomainError) -> int:
    for cls in type(exc).__mro__:
        if cls in STATUS:
            return STATUS[cls]
    return 400  # a refusal nobody mapped yet: your call

def install(app: FastAPI) -> None:
    @app.exception_handler(DomainError)
    async def on_domain_error(
        request: Request, exc: DomainError
    ) -> JSONResponse:
        return JSONResponse(
            status_code=status_for(exc),
            content={
                "error": type(exc).__name__,
                "detail": str(exc),
            },
        )
Enter fullscreen mode Exit fullscreen mode

One handler on the base class is enough. Starlette finds the handler by walking the exception's method resolution order, so a handler registered for DomainError catches every subclass; you can read the lookup loop in Starlette's source. status_for walks the MRO the same way, so a future OrderNotFound subclass still gets its 404.

The path operation stops caring about errors at all:

@router.post("/orders/{order_id}/cancel")
def cancel(order_id: str, repo: Repo = Depends(get_repo)):
    order = cancel_order(repo, order_id)
    return {"id": order.id, "status": order.status}
Enter fullscreen mode Exit fullscreen mode

The tests that get simpler

The rule test now says what the rule is, with no HTTP in sight:

# tests/test_orders.py  (after)
import pytest

from app.domain.errors import OrderAlreadyShipped
from app.services.orders import cancel_order

def test_cannot_cancel_shipped(shipped_order_repo):
    with pytest.raises(OrderAlreadyShipped):
        cancel_order(shipped_order_repo, "o-1")
Enter fullscreen mode Exit fullscreen mode

The HTTP contract still gets tested, once, at the edge, where it lives. A tiny app with a route that raises is enough, using FastAPI's TestClient (it needs httpx installed):

from fastapi import FastAPI
from fastapi.testclient import TestClient

from app.domain.errors import OrderAlreadyShipped
from app.http.errors import install

def test_shipped_maps_to_409():
    app = FastAPI()
    install(app)

    @app.get("/boom")
    def boom():
        raise OrderAlreadyShipped("o-1")

    resp = TestClient(app).get("/boom")
    assert resp.status_code == 409
    assert resp.json()["error"] == "OrderAlreadyShipped"
Enter fullscreen mode Exit fullscreen mode

Ten rule tests and one mapping test, instead of ten rule tests that each re-assert the HTTP contract. If you ever change 409 to 422, one line in STATUS and one assertion move.

The CLI now catches something it understands:

import typer

from app.domain.errors import DomainError
from app.services.orders import cancel_order
from app.wiring import build_order_repo

cli = typer.Typer()

@cli.command()
def cancel(order_id: str) -> None:
    try:
        cancel_order(build_order_repo(), order_id)
    except DomainError as exc:
        typer.echo(f"refused: {exc}", err=True)
        raise typer.Exit(code=1)
Enter fullscreen mode Exit fullscreen mode

The queue worker gets the same clarity: catch OrderNotFound and drop the message, since a retry will not make the order exist, and let anything that is not a DomainError go back on the queue for another attempt.

A clean orange hexagon core emitting plain domain errors, with a single adapter at the HTTP edge converting them into status codes
One translation point: the core names the refusal, the HTTP adapter picks the status code.

Why coding agents make this worse

Anthropic's Claude Code best-practices page says Claude "starts every task by reading your code" and will find "your conventions, your test framework, and how existing components are built". That is a feature. It is also why a pattern in your repo is a pattern your agent repeats.

Ask an agent to add refund_order to a codebase where every service raises HTTPException, and the most consistent thing it can do is raise HTTPException again. It is matching the house style, which is what you asked it to do. Each new service written that way becomes one more example for the next session, so the leak spreads faster than any one person would spread it by hand.

The same docs page gives you the counter-move. It says CLAUDE.md works best for things Claude can't work out from the code, including "an old pattern that's everywhere but that new code must not copy". So write it down:

# Conventions
- Services and domain code raise errors from app/domain/errors.py.
- Never import fastapi or starlette outside app/http/.
Enter fullscreen mode Exit fullscreen mode

Then make it a check instead of a wish. import-linter has a forbidden contract, and its docs say "External packages may also be forbidden" as long as include_external_packages is switched on:

[tool.importlinter]
root_package = "app"
include_external_packages = true

[[tool.importlinter.contracts]]
name = "Core stays HTTP-free"
type = "forbidden"
source_modules = ["app.domain", "app.services"]
forbidden_modules = ["fastapi", "starlette"]
Enter fullscreen mode Exit fullscreen mode

Run lint-imports in CI and in whatever check your agent runs before it calls a task done. The first time it reaches for HTTPException inside app/services/, the contract fails and the agent gets a concrete error to fix instead of a style preference to guess at.

Where HTTPException still belongs

Keep raising it where Starlette says to: in endpoints, and in HTTP-layer dependencies such as auth checks, header parsing and request-shaped validation. Those already know they are serving a request. Start with the grep from the top of this post: move the first service it finds to a domain error, add the handler, and let lint-imports hold the line for the rest.


If this was useful

The split in this post (a core that refuses in its own language, adapters at the edge that translate) is the central idea of Hexagonal Architecture in Python. The book builds one async FastAPI + SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered and vertical slice), then measures them, so you can see where each boundary lands in each style. Every listing runs from the free companion repo if you want to read the code before the prose.

Hexagonal Architecture in Python by Gabriel Anhaia

Top comments (0)