Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inflect from snake case to camel case post the pydantic schema validations

I can able to find a way to convert camelcase type based request body to snake case one by using Alias Generator, But for my response, I again want to inflect snake case type to camel case type post to the schema validation. Is there any way I can achieve this?

Example: I do have a python dict as below,

{
 "title_name": "search001",
 "status_type": "New" 
}

And post to the pydantic schema validation my dict should convert snake case type to camel case as below,

{
 "titleName": "search001",
 "statusType": "New" 
}

How can I define a pydantic schema to achieve the above problem?

Thanks in advance.

like image 416
saravana kumar Avatar asked Sep 06 '25 16:09

saravana kumar


1 Answers

If you've upgraded Pydantic to v2, you can implement it in a really easy way using alias generators:

from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_camel


class BaseSchema(BaseModel):
    model_config = ConfigDict(
        alias_generator=to_camel,
        populate_by_name=True,
        from_attributes=True,
    )

class UserSchema(BaseSchema):
    id: int
    name: str
like image 137
aryadovoy Avatar answered Sep 10 '25 02:09

aryadovoy