Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a strict json schema with pydantic?

I recently started to use pydandic to generate JSON schemas for validating data but I found the by default the generated schema does not complain about unknown keys inside my BaseModel.

Example:

class Query(BaseModel):
    id: str
    name: Optional[str]

The generated schema would pass validation even if the object has other attributes than the two one mentioned here.

How can I assure validation will fail if someone adds a "foo: bar" property?

like image 348
sorin Avatar asked Mar 02 '23 18:03

sorin


1 Answers

You need to use a configuration on your model:

from pydantic import BaseModel, Extra
class Query(BaseModel):
    id: str
    name: Optional[str]
    class Config:
        extra = Extra.forbid

It defaults to Extra.ignore, the other option is Extra.allow which adds any extra fields to the resulting object.

You can also just use the strings "ignore", "allow", or "forbid"

Here are all the model config options you can use:

https://pydantic-docs.helpmanual.io/usage/model_config/

like image 148
juanpa.arrivillaga Avatar answered Mar 14 '23 21:03

juanpa.arrivillaga