リクエストのバリデーションエラーによる HTTP status=422 のレスポンスは、
FastAPI デフォルトでは、以下のような JSON のレスポンスを返してしまう。
パスパラメータに整数(int)を期待するところに数値に解析できない文字列でリクエストをした時、
{ "detail": [ { "type": "int_parsing", "loc": [ "path", "id" ], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "a123" } ] }
これをエラーに従った任意のレスポンスを返すようにするには、以下ように
リクエストバリデーションエラー(RequestValidationError)のハンドラーを定義する。
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): excs = eval(exc.__str__()) return JSONResponse(content={"errormesage":excs[0].get('msg')}, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)
JSONResponse の content で任意のレスポンスを返すように設定する。
すると、エラーで以下のようにレスポンスを返すようになる。
{ "errormesage": "Input should be a valid integer, unable to parse string as an integer" }