Open1
FastAPI例外ハンドラ:レスポンスカスタマイズ

FastAPIではリクエストのエラーを自動検知、例外ハンドラでレスポンスを自由にカスタマイズ可
以下に2パターンをコード例とレスポンス内容で比較してまとめます(メモ)
自前カスタム例
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
return PlainTextResponse(str(exc), status_code=400)
レスポンス例
/items/{item_id}
のitem_id
はint
$ curl http://127.0.0.1:8000/items/abc
[
{
'type': 'int_parsing',
'loc': ('path', 'item_id'),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'abc'
}
]
特徴
- 文字列化しただけ
- Pythonのリスト・タプル表記
- クライアント側でパースしにくい
公式ハンドラを再利用する例
from fastapi.exception_handlers import request_validation_exception_handler
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
print(f"OMG! The client sent invalid data!: {exc}")
return await request_validation_exception_handler(request, exc)
レスポンス例
/items/{item_id}
のitem_id
はint
$ curl http://127.0.0.1:8000/items/abc
{
"detail": [
{
"type": "int_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "abc"
}
]
}
特徴
- 公式のエラーフォーマット
- JSON準拠
- クライアント側で扱いやすい
違いまとめ
レスポンス形式 | 内容の形 | 特徴 | |
---|---|---|---|
自前カスタム | text/plain | Python表記の文字列 | シンプルだがパースしにくい |
公式ハンドラ | application/json | 構造化JSON | 標準的で扱いやすい |