typestar

Errors and status codes in Python

HTTPException is how a handler refuses, with the status you choose.

from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient

app = FastAPI()
TOURS = {"basics": 60}


class TourMissing(Exception):
    def __init__(self, slug):
        self.slug = slug


@app.exception_handler(TourMissing)
def handle_missing(request, exc):
    return JSONResponse(status_code=404, content={"error": exc.slug})


@app.get("/tours/{slug}")
def tour(slug: str):
    if slug == "gone":
        raise HTTPException(status_code=410, detail="that tour retired")
    if slug not in TOURS:
        raise TourMissing(slug)
    return {"slug": slug, "steps": TOURS[slug]}


client = TestClient(app)
print(client.get("/tours/basics").json())
print(client.get("/tours/gone").status_code, client.get("/tours/gone").json())
print(client.get("/tours/nope").status_code, client.get("/tours/nope").json())

How it works

  1. Raise it; do not return an error dict with a 200.
  2. detail is what the client sees in the body.
  3. An exception handler maps your own error types onto responses.

Keywords and builtins used here

The run, in numbers

Lines
31
Characters to type
830
Tokens
222
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 121 seconds.

Type this snippet

Step 4 of 4 in FastAPI routes, step 9 of 19 in Web services & data access.

← Previous Next →