Integer and string cannot be distinguished with pydantic

Viewed 3278
from pydantic import BaseModel


class AuthenticationResponseSchema(BaseModel):
    type: str
schema = AuthenticationResponseSchema(type=1)

Now I'm changing marshmallow to pydantic for schema, model ...

But pydantic schema did not validated type when data response.

data type of type is string, but the integer passed too.

what is wrong?

Thank you.

1 Answers

As statad in the documentation

strings are accepted as-is, int float and Decimal are coerced using str(v), bytes and bytearray are converted using v.decode(), enums inheriting from str are converted using v.value, and all other types cause an error

If you want to force string, there's this thing called Strict Types, so you can use StrictStr.

from pydantic import BaseModel, StrictStr


class AuthenticationResponseSchema(BaseModel):
    type: StrictStr


schema = AuthenticationResponseSchema(type=1)

Related