FASTAPI & Pydantic: How to specify possible values for a field in pydantic.Basemodel

Viewed 3640

I have a model like :

# Imports
from pydantic import BaseModel

# Data Models
class MyModel(BaseModel):
    a: str
    b: str
    c: str

@app.post('/endpoint_to_post')
async def post_log(my_model: MyModel):

I want to specify some constraint on this model. Indeed, I need a possible values constraint on the field C of the model MyModel.

Like:

# Imports
from pydantic import BaseModel

# Data Models
class MyModel(BaseModel):
    a: str
    b: str
    c: str in ['possible_value_1', 'possible_value_2']

Thank for your help :)

2 Answers

You can use enum from Python stdlib:

from enum import Enum
from pydantic import BaseModel


class CEnum(Enum):
    VALUE_1 = 'possible_value_1'
    VALUE_2 = 'possible_value_2'


# Data Models
class MyModel(BaseModel):
    a: str
    b: str
    c: CEnum

Pydantic will automatically convert any string matching the enum value to the correct enum instance and will raise ValidationError if it doesn't match anything. You can combine it with Optional or Union from Python's typing to either make this field optional or to allow other types as well (the first matching type from all types passed to Union will be used by Pydantic, so you can create a "catch-all" scenario using Union[CEnum, str]).

I found a solution,

I used pydantic.validator to achieve this.

Example:

# Imports
from pydantic import BaseModel, validator

# Data Models
class MyModel(BaseModel):
    a: str
    b: str
    c: str # in ['possible_value_1', 'possible_value_2']

    @validator('c')
    def c_match(cls, v):
        if not v in ['possible_value_1', 'possible_value_2']:
            raise ValueError('c must be in [possible_value_1, possible_value_2]')
        return v

cf https://pydantic-docs.helpmanual.io/usage/validators/

Related