# Raising Your Own Exceptions in an API

An API's own rules raise exception classes named for each problem, such as TicketNotFound and StatusChangeNotAllowed, from plain functions that know nothing about HTTP, and @app.exception_handler turns each one into a status code and a JSON body, such as 404 or 409.

Journeyman · FastAPI · REST API · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Write your own exception classes for the problems an API knows about, and raise them from plain functions that know nothing about HTTP
- Turn each of your own exceptions into a status code and a JSON body with @app.exception_handler, such as 404 or 409

## Key takeaways

- A helper that raises HTTPException works only inside a web request. Any other program that uses it, such as a script, gets a web answer it has nowhere to send.
- Your own exception class, such as class TicketNotFound(Exception), names a problem your API knows about. Plain functions raise it and stay free of HTTP.
- With no handler, FastAPI doesn't know what your exception means, so the caller gets 500 Internal Server Error.
- @app.exception_handler(TicketNotFound) turns that exception into an answer. The handler gets the request and the exception, and returns a JSONResponse with a status code and a body.
- 409 Conflict means the request clashes with the way things are now, such as a ticket that's waiting being sent straight to ready.

Every API has rules of its own: a seat that's already taken, an order that's already shipped, a coupon that has run out. Each broken rule has to reach the caller as the right status code, but the code that checks the rule shouldn't have to know about status codes at all. This lesson keeps the two apart, the way larger FastAPI projects do.

The example is Spoke & Chain Bike Repair's tickets API from *Create, Update and Delete: POST, PUT, PATCH and DELETE*, with the shop's ticket code now in its own file, `shop.py`.

## A helper that only works on the web

The mechanics have a small script at the workbench, `scan.py`. It reads ticket numbers from a barcode scanner and shows each bike. It uses the API's own `find_ticket`, the one that raises `HTTPException` when there's no such ticket:

```python
from shop import find_ticket

for number in [2, 29]:
    ticket = find_ticket(number)
    print(f"Ticket {number}: {ticket['bike']}")
```

The scanner misread a 9 as 29. The script prints `Ticket 2: red road bike`, then stops, and the last line of its error reads:

```text
fastapi.exceptions.HTTPException: 404: There's no ticket 29.
```

A 404 means something to a browser or a phone app, but here there's no request and nobody to answer: only a script that now needs to know HTTP status codes to handle a typo. `find_ticket` knows too much.

Think of a restaurant. When the soup runs out, the cook says "we're out of soup". The cook doesn't walk into the dining room; the waiter decides how to tell each guest. An API works best the same way: the shop's code names the problem, and the web part decides what the caller hears.

## Your own exception classes

An exception class of your own names one problem. `class TicketNotFound(Exception):` makes a new kind of exception: the `Exception` in the parentheses says it's a kind of `Exception`, so `raise` and `except` work with it as with `ValueError` (*Handling Errors with try and except*). A docstring is all its body needs. Here's `shop.py`, with no FastAPI in it:

```python
TICKETS = [
    {"id": 1, "customer": "Dana", "bike": "blue cruiser", "problem": "flat rear tire", "status": "waiting"},
    {"id": 2, "customer": "Marco", "bike": "red road bike", "problem": "brakes squeal", "status": "in repair"},
    {"id": 3, "customer": "Ana", "bike": "green hybrid", "problem": "chain keeps slipping", "status": "ready"},
]

NEXT_STEP = {"waiting": "in repair", "in repair": "ready", "ready": "picked up"}


class TicketNotFound(Exception):
    """There's no ticket with the id that was asked for."""


class StatusChangeNotAllowed(Exception):
    """A ticket can't move from its status to the one that was asked for."""


def find_ticket(ticket_id):
    for ticket in TICKETS:
        if ticket["id"] == ticket_id:
            return ticket
    raise TicketNotFound(f"There's no ticket {ticket_id}.")
```

The message goes in the parentheses when it's raised, and `str(error)` gives it back. Now the script catches the problem by its name:

```python
from shop import TicketNotFound, find_ticket

for number in [2, 29]:
    try:
        ticket = find_ticket(number)
        print(f"Ticket {number}: {ticket['bike']}")
    except TicketNotFound as error:
        print(error)
```

```text
Ticket 2: red road bike
There's no ticket 29.
```

The API's route still calls `find_ticket`, but FastAPI has never heard of `TicketNotFound`. `GET /tickets/99` now answers 500 Internal Server Error, with the plain text `Internal Server Error`: to FastAPI, any exception it doesn't know is a crash.

## @app.exception_handler: from exception to answer

`@app.exception_handler(TicketNotFound)` (read "at app dot exception handler") tells FastAPI what to answer when that exception reaches it, from any route. The handler gets the request and the exception, `exc`, and returns a `JSONResponse`: a status code and the body to send.

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

from shop import StatusChangeNotAllowed, TicketNotFound, change_status, find_ticket

app = FastAPI(title="Spoke & Chain")


@app.exception_handler(TicketNotFound)
def ticket_not_found(request: Request, exc: TicketNotFound):
    return JSONResponse(status_code=404, content={"detail": str(exc)})


@app.exception_handler(StatusChangeNotAllowed)
def status_change_not_allowed(request: Request, exc: StatusChangeNotAllowed):
    return JSONResponse(status_code=409, content={"detail": str(exc)})
```

The handler has to take `request`, even when it doesn't use it. `GET /tickets/99` answers 404 again, with `{"detail":"There's no ticket 99."}`, and the route itself is one line, `return find_ticket(ticket_id)`.

The second handler is for the shop's main rule: a ticket moves one step at a time, waiting, in repair, ready, picked up. `change_status(ticket, new_status)`, in `shop.py`, moves the ticket when `new_status` is its next step in `NEXT_STEP`, and otherwise raises `StatusChangeNotAllowed`. (The Do It below writes it.) Its route takes the new status, one of four, with `Literal` from *Field Rules: Lengths, Ranges and Choices*:

```python
class StatusChange(BaseModel):
    status: Literal["waiting", "in repair", "ready", "picked up"]


@app.patch("/tickets/{ticket_id}/status")
def update_status(ticket_id: int, change: StatusChange):
    ticket = find_ticket(ticket_id)
    return change_status(ticket, change.status)
```

`PATCH /tickets/1/status` with `{"status": "in repair"}` answers 200 with Dana's ticket, now in repair. `PATCH /tickets/3/status` with `{"status": "waiting"}` answers 409 Conflict, which means "that clashes with the way things are now":

```json
{"detail":"Ticket 3 is ready, so it can't go to waiting."}
```

## Why the rules don't know about HTTP

`shop.py` never imports FastAPI. The same `find_ticket` and `change_status` serve the API, the workbench script and, in the next chapter, the tests, and each caller handles the problems its own way. The handlers are the one place where a problem becomes a status code: if the shop decides a refused change should be a 422, that's one line. And a new route that changes a status gets its 409 without a line of error code.

## Do it: refuse a step the shop doesn't allow

Write the shop's main rule. A ticket moves one step at a time, and `NEXT_STEP` (in the starter) gives the step after each status. A ticket that's picked up has no next step.

- `ticket`: a ticket dictionary, with the keys `id`, `customer`, `bike`, `problem` and `status`.
- `new_status`: the status the ticket should move to, such as `"in repair"`.

**Your job:** write the exception class `StatusChangeNotAllowed`, a kind of `Exception`, and the function `change_status(ticket, new_status)`.

- When `new_status` is the ticket's next step in `NEXT_STEP`, set the ticket's `"status"` to `new_status` and return the ticket.
- Otherwise, change nothing and raise `StatusChangeNotAllowed` with the message `Ticket 1 is waiting, so it can't go to ready.`, with the ticket's id, its status and `new_status` in their places.

Worked through: Dana's ticket, id 1, is waiting, and `NEXT_STEP["waiting"]` is `"in repair"`. So `change_status(dana, "in repair")` returns her ticket with the status `"in repair"`, and `change_status(dana, "ready")` raises `StatusChangeNotAllowed` with the message `Ticket 1 is waiting, so it can't go to ready.`

Practiced live on the lesson page: write the Python right there and check it.

## Check yourself

2 questions to try on the lesson page.

## So what

Exceptions named for your API's own problems keep the rules in plain Python that any program can use, and one handler for each turns it into the status code a caller expects.

## Key terms

- [Custom Exception](https://www.ask-codey.com/glossary/custom-exception)
- [Exception Handler](https://www.ask-codey.com/glossary/exception-handler-fastapi)
- [409 Conflict](https://www.ask-codey.com/glossary/409-conflict)

## Related

- [Create, Update and Delete: POST, PUT, PATCH and DELETE](https://www.ask-codey.com/lessons/fastapi-rest-create-update-delete)
- [One Error Shape for the Whole API](https://www.ask-codey.com/lessons/fastapi-errors-one-shape)
- [Handling Errors with try and except](https://www.ask-codey.com/lessons/python-exceptions-try-except)

Source: https://www.ask-codey.com/lessons/fastapi-errors-your-own-exceptions
