Is it possible to reject requests with fields that does not map to the request model?
The use case is that we want to alert users that they have misspelt an optional field. For example we have something like
from typing import Optional
from pydantic import BaseModel
from fastapi import FastAPI
class Item(BaseModel):
id_: str
description: Optional[str] = None
APP = FastAPI()
@APP.post("/items/")
def create_item(item: Item):
return item
And do a post like
curl -X POST "http://127.0.0.1:8000/items/" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"id_\":\"string\",\"pescripton\":\"string\"}"
Note misspelled description.
Then the response will be
{
"id_": "string",
"description": null
}
Can we configure FastApi and pydantic to reject this instead?
Try adding
class Config:
extra = “forbid”
inside the class definition of Item. I think that should make it raise errors if it receives unexpected fields.
Thanks @dmontagu! This is exactly what I was looking for.
Thanks for the help here @dmontagu ! :cake: :bowing_man:
Thanks @m-johansson for reporting back and closing the issue :+1:
Most helpful comment
Try adding
inside the class definition of
Item. I think that should make it raise errors if it receives unexpected fields.