Fastapi: [QUESTION] Could we reject request bodies with misspelt optional fields?

Created on 22 Jan 2020  Â·  3Comments  Â·  Source: tiangolo/fastapi

First check

  • [x] I used the GitHub search to find a similar issue and didn't find it.
  • [x] I searched the FastAPI documentation, with the integrated search.
  • [x] I already searched in Google "How to X in FastAPI" and didn't find any information.

Description

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?

question

Most helpful comment

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.

All 3 comments

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:

Was this page helpful?
0 / 5 - 0 ratings