Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require predefined string values in python pydantic basemodels?

Is there any in-built way in pydantic to specify options? For example, let's say I want a string value that must either have the value "foo" or "bar".

I know I can use regex validation to do this, but since I use pydantic with FastAPI, the users will only see the required input as a string, but when they enter something, it will give a validation error. All in-built validations of pydantic are displayed in the api interface, so would be great if there was something like

class Input(BaseModel):
     option: "foo" || "bar"
like image 242
Gabriel Petersson Avatar asked Apr 15 '20 20:04

Gabriel Petersson


People also ask

What is __ root __ In Pydantic?

Pydantic models can be defined with a custom root type by declaring the __root__ field. The root type can be any type supported by pydantic, and is specified by the type hint on the __root__ field.

What is Pydantic Constr?

constr is a specific type that give validation rules regarding this specific type. You have equivalent for all classic python types.

What is Pydantic in Python?

Pydantic is a useful library for data parsing and validation. It coerces input types to the declared type (using type hints), accumulates all the errors using ValidationError & it's also well documented making it easily discoverable.

What is alias in Pydantic?

See also MongoDB Field Names. While in Pydantic, the underscore prefix of a field name would be treated as a private attribute. The alias is defined so that the _id field can be referenced.


1 Answers

Yes, you can either use an enum:

class Choices(Enum):
    foo = 'foo'
    bar = 'bar'

class Input(BaseModel):
     option: Choices

see here

Or you can use Literal:

class Input(BaseModel):
     option: Literal['foo', 'bar']

see here

like image 163
SColvin Avatar answered Sep 28 '22 04:09

SColvin