FastAPI エラー処理
API 開発では、クライアントにエラー情報を返す必要があります。FastAPI はHTTPExceptionを使用して HTTP エラーをスローでき、より複雑なエラーシナリオを処理するためのカスタム例外ハンドラーもサポートしています。
HTTPException を使用する
エラーレスポンスを返す必要がある場合は、スローします。HTTPException:
実例
app = FastAPI()
items = {"foo": "The Foo Wrestlers", "bar": "The Bar Fighters"}
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id not in items:
# リソースが存在しない場合、404 エラーをスローする
raise HTTPException(status_code=404, detail="Item not found")
return {"item": items[item_id]}
にアクセスしhttp://127.0.0.1:8000/items/42たとき、次のように返されます:
{
"detail": "Item not found"
}
HTTP ステータスコードは404。
ここで使用しているのは
raiseではなくreturn。HTTPExceptionは例外です。スローされると FastAPI がそれをキャッチして、対応する HTTP エラーレスポンスを返します。これは Python の例外処理メカニズムと一致しています。
HTTPException のパラメータ
| パラメータ | 型 | 説明 |
|---|---|---|
status_code | int | HTTP ステータスコード(必須) |
detail | Any | エラー詳細。文字列、辞書、リストなどを指定可能 |
headers | dict | None | 追加のレスポンスヘッダー(オプション) |
カスタムエラー詳細
detaildetail パラメータは任意の型を指定でき、文字列に限定されません:
実例
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id == "invalid":
# detail は辞書にでき、より多くのエラー情報を含めることができます
raise HTTPException(
status_code=400,
detail={
"error_code": "INVALID_ID",
"message": 「商品IDの形式が正しくありません」,
"hint": 「英数字を組み合わせたIDを使用してください」
}
)
return {"item_id": item_id}
カスタムレスポンスヘッダーの追加
一部のシナリオでは、エラーレスポンスにカスタムレスポンスヘッダーを追加する必要があります:
実例
app = FastAPI()
@app.get("/items-header/{item_id}")
async def read_item_header(item_id: str):
if item_id == "invalid":
raise HTTPException(
status_code=404,
detail="Item not found",
headers={"X-Error": "There goes my error"}, # カスタムレスポンスヘッダー
)
return {"item": item_id}
クライアントのリクエスト頻度を制限(レート制限)する必要があるシナリオでは、エラーレスポンスヘッダーに
Retry-Afterヘッダーを追加して、クライアントにいつ再試行できるかを知らせることができます。
カスタム例外ハンドラー
カスタム例外や組み込み例外のハンドラーを登録して、エラーレスポンス形式を統一できます:
実例
from fastapi.responses import JSONResponse
# カスタム例外クラス
class UnicornException(Exception):
def __init__(self, name: str):
self.name = name
app = FastAPI()
# 例外ハンドラーを登録
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
# カスタム形式のエラーレスポンスを返す
return JSONResponse(
status_code=418,
content={"message": f"Oops! {exc.name} did something wrong"},
)
@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
if name == "yolo":
# カスタム例外をスロー
raise UnicornException(name=name)
return {"unicorn_name": name}
デフォルト例外ハンドラーのオーバーライド
FastAPI にはデフォルトの例外ハンドラーがあります。これらをオーバーライドしてエラーレスポンス形式をカスタマイズできます:
実例
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
app = FastAPI()
# HTTP 例外ハンドラーをオーバーライド
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
return JSONResponse(
status_code=exc.status_code,
content={"error": f"HTTP error: {exc.detail}"},
)
# リクエスト検証例外ハンドラーをオーバーライド
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content={"error": 「データ検証に失敗しました」, "details": exc.errors()},
)
RequestValidationErrorは、FastAPI がリクエストデータの検証に失敗したときにスローする例外です。そのハンドラーをオーバーライドすると、検証エラーのレスポンス形式をカスタマイズできます。
リダイレクト
を使用してRedirectResponseリダイレクトを実現します:
実例
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get("/items/")
async def read_items():
return {"items": ["foo", "bar"]}
@app.get("/redirect")
async def redirect():
# /items/ にリダイレクト
return RedirectResponse(url="/items/")
カスタムレスポンスヘッダーとステータスコード
を使用してJSONResponseレスポンスヘッダーとステータスコードをカスタマイズします:
実例
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
content = {"item_id": item_id}
headers = {"X-Custom-Header": "custom-header-value"}
return JSONResponse(content=content, headers=headers)
まとめ
- を使用して
raise HTTPExceptionHTTP エラーレスポンスを返します detaildetail パラメータは任意の型(文字列、辞書、リストなど)を指定できます- を使用して
@app.exception_handlerカスタム例外ハンドラーを登録します - FastAPI のデフォルト例外ハンドラーをオーバーライドしてエラー形式を統一できます
- を使用して
RedirectResponseリダイレクトを実現します