21

I'm looking for some library or example of code to format FastAPI validation messages into human-readable format. E.g. this endpoint:

@app.get("/")
async def hello(name: str):
    return {"hello": name}

Will produce the next json output if we miss name query parameter:

{ 
    "detail":[ 
        { 
            "loc":[ 
                "query",
                "name"
            ],
            "msg":"field required",
            "type":"value_error.missing"
        }
    ]
}

So my questions is, how to:

  1. Transform it into something like "name field is required" (for all kinds of possible errors) to show in toasts.
  2. Use it to display form validation messages
  3. Generate forms themselves from api description if it's possible
imbolc
  • 1,620
  • 1
  • 19
  • 32
  • Please see related answers [here](https://stackoverflow.com/a/72833284/17865804), [here](https://stackoverflow.com/a/71682274/17865804) and [here](https://stackoverflow.com/a/70954531/17865804), as well as have a look at [this](https://stackoverflow.com/a/71228281/17865804), [this](https://stackoverflow.com/a/72003724/17865804) and [this](https://stackoverflow.com/a/73151350/17865804). – Chris Nov 03 '22 at 11:04

3 Answers3

14

FastAPI has a great Exception Handling, so you can customize your exceptions in many ways.

You can raise an HTTPException, HTTPException is a normal Python exception with additional data relevant for APIs. But you can't return it you need to raise it because it's a Python exception

from fastapi import HTTPException
...
@app.get("/")
async def hello(name: str):
    if not name:
        raise HTTPException(status_code=404, detail="Name field is required")
    return {"Hello": name}

By adding name: str as a query parameter it automatically becomes required so you need to add Optional

from typing import Optional
...
@app.get("/")
async def hello(name: Optional[str] = None):
    error = {"Error": "Name field is required"}
    if name:
        return {"Hello": name}
    return error

$ curl 127.0.0.1:8000/?name=imbolc
{"Hello":"imbolc"}
...
$ curl 127.0.0.1:8000
{"Error":"Name field is required"}

But in your case, and i think this is the best way to handling errors in FastAPI overriding the validation_exception_handler:

from fastapi import FastAPI, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
...
@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(), "Error": "Name field is missing"}),
    )
...
@app.get("/")
async def hello(name: str):
    return {"hello": name}

You will get a response like this:

$ curl 127.0.0.1:8000

 {
   "detail":[
      {
         "loc":[
            "query",
            "name"
         ],
         "msg":"field required",
         "type":"value_error.missing"
      }
   ],
   "Error":"Name field is missing"
}

You can customize your content however if you like:

{
"Error":"Name field is missing",
   "Customize":{
      "This":"content",
      "Also you can":"make it simpler"
   }
}
Yagiz Degirmenci
  • 16,595
  • 7
  • 65
  • 85
  • 2
    Not one of a great ideas to override `validation_exception_handler` and hardcode an error message in there; basically you can apply it only on a hello world example.. – Michele Mar 15 '22 at 08:47
  • @Michele,, you can basically handle all the cases since you have access to the `Request` object or the `RequestValidationError `. – Yagiz Degirmenci Jun 27 '23 at 11:39
  • @Erez, you have validation out-of-box without doing anything, yes FastAPI is great at error handling, if your expectation is the handle all the cases error cases without writing any code, I have bad news for you. – Yagiz Degirmenci Jun 27 '23 at 11:40
6

I reached here with a similar question - and I ended up handling the RequestValidationError to give back a response where every field is an array of the issues with that field. The response to your request would become (with a status_code=400)

    {
        "detail": "Invalid request",
        "errors": {"name": ["field required"]}
    }

that's quite handy to manage on the frontend for snackbar notifications and flexible enough.

Here's the handler


from collections import defaultdict

from fastapi import status
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse


@app.exception_handler(RequestValidationError)
async def custom_form_validation_error(request, exc):
    reformatted_message = defaultdict(list)
    for pydantic_error in exc.errors():
        loc, msg = pydantic_error["loc"], pydantic_error["msg"]
        filtered_loc = loc[1:] if loc[0] in ("body", "query", "path") else loc
        field_string = ".".join(filtered_loc)  # nested fields with dot-notation
        reformatted_message[field_string].append(msg)

    return JSONResponse(
        status_code=status.HTTP_400_BAD_REQUEST,
        content=jsonable_encoder(
            {"detail": "Invalid request", "errors": reformatted_message}
        ),
    )

Dariosky
  • 371
  • 4
  • 8
3

I think the best I can come up with is actually PlainTextResponse

Adding these:

from fastapi.exceptions import RequestValidationError

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return PlainTextResponse(str(exc), status_code=400)

You get a more human-friendly error message like these in plain text:

1 validation error
path -> item_id
  value is not a valid integer (type=type_error.integer)

It's well documented in FastAPI docs here.

tomy0000000
  • 323
  • 3
  • 8