How to require predefined string values in python pydantic basemodels?

Question:

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"
Asked By: Gabriel Petersson

||

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

Answered By: SColvin

Wanted to add another option here. You could also use a Regex. Worked better for me since Literal isn’t available until python 3.8 (which is unfortunately not an easy upgrade for me) and since I’m only expecting a single string for each, enum didn’t really fit.

class YourClass(pydantic.BaseModel):
  your_attribute: pydantic.constr(regex="^yourvalwith.escapes/abcd$")
Answered By: Steven Staley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.