Search code examples
pythonpython-3.xfastapipydantic

Pydantic accept integer as string input


For a FastAPI Pydantic interface I want to be as tolerable as possible, such as receiving an integer for a string parameter and parse that integer to string:

from pydantic import BaseModel

class FooBar(BaseModel):
    whatever: str
    
FooBar(whatever=12)

Gives:

ValidationError: 1 validation error for FooBar
whatever
  Input should be a valid string [type=string_type, input_value=12, input_type=int]
    For further information visit https://errors.pydantic.dev/2.4/v/string_type

I think in earlier versions this was possible.

  • Python 3.10
  • pydantic==2.4.2
  • pydantic_core==2.10.1

Solution

  • This functionality was just reintroduced in version 2.4.0. You need to add the coerce_numbers_to_str configuration:

    from pydantic import BaseModel, ConfigDict
    
    class FooBar(BaseModel):
        model_config = ConfigDict(coerce_numbers_to_str=True)
    
        whatever: str