Fastapi change error measage

Теги: fastapi  python 

В фастапи сообщение ошибки выглядит примерно так

{"detail": [
{
    "loc": [
        "body",
        "location",
        "name"
    ],
    "msg": "field required",
    "type": "value_error.missing"
},
{
    "loc": [
        "body",
        "location",
        "name12"
    ],
    "msg": "extra fields not permitted",
    "type": "value_error.extra"
}
]
}

Текст ошибки задан в fastapi.exceptions. Класс можно переопределить

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

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=jsonable_encoder({"detail": exc.errors(),
                "body": exc.body,
                 "your_additional_errors": {"Will be": "Inside", "This":" Error message"}}),
    )

class Item(BaseModel):
    title: str
    size: int

@app.post("/items/")
async def create_item(item: Item):
    return item

Теперь передав в body

{
 "title": 22,
 "size": "hehe"
}

Мы получим ответ

{
  "detail": [
    {
      "loc": [
        "body",
        "size"
      ],
      "msg": "value is not a valid integer",
      "type": "type_error.integer"
    }
  ],
  "body": {
    "title": 22,
    "size": "hehe"
  },
  "your_additional_errors": {
    "Will be": "Inside the",
    "Error": "Message"
  }
}

Другой вариант - через [fastapi-middleware]