Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 949
Joost Döbken Avatar asked Nov 07 '25 23:11

Joost Döbken


1 Answers

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
like image 97
M.O. Avatar answered Nov 09 '25 15:11

M.O.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!