LoginSignup
9
6

More than 1 year has passed since last update.

FastAPIの422エラー(Unprocessable Entity)をデバッグする

Posted at

はじめに

FastAPIを利用していると、たびたび422エラーが発生することがあります。
これは主に「リクエストのデータの型が、サーバが期待しているものと異なる」場合に発生します。
デフォルト状態では、FastAPIはこの様なエラーが発生した際に、その詳細について出力しません。
そのため、なぜエラーが起きたか?を確認できず、しばしば困ったことになります。

今回はデバッグ向けに、422エラーが発生した際にログを出力するように設定しよう、というの内容です。

解決方針

FastAPIがリクエストのバリデーションに失敗した際のカスタム例外ハンドラを設定し、
422エラーを返す際にエラー内容を出力するようにします。

実装

例として、POSTのエンドポイントを用意します。

from pydantic import BaseModel
from fastapi import FastAPI,

app = FastAPI()

class Name(BaseModel):
    name:str

@app.post("/name")
def _name(data:Name):
    return {"name":data.name}

このアプリケーションにexception_handlerを登録します。
このハンドラーは、アプリケーションでエラーが発生した際に呼び出す関数を設定することができます。
今回はRequestValidationErrorが発生した際に呼び出されるように設定しました。

from pydantic import BaseModel
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse

app = FastAPI()

@app.exception_handler(RequestValidationError)
async def handler(request:Request, exc:RequestValidationError):
    print(exc)
    return JSONResponse(content={}, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)


class Name(BaseModel):
    name:str

@app.post("/name")
def _name(data:Name):
    return {"name":data.name}

そして、例えば{"nama":"Taro"}のような誤ったデータをPOSTしてしまうと以下のような内容が出力されます。

1 validation error for Request
body -> name
  field required (type=value_error.missing)

これでPOSTしたデータの誤りを確認することができますね。

まとめ

今回はFastAPIの422エラーが発生した際に、その詳細を出力する方法を見てきました。
紹介した例のように、単なるデバッグ目的の場合はprintを利用する方法でよいかとは思いますが、
しっかりログを記録したい場合はloggerの利用を検討したほうが良いでしょう。

参考

Handling Errors - FastAPI

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6