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,
JavaScript
x
5
1
{
2
"title_name": "search001",
3
"status_type": "New"
4
}
5
And post to the pydantic schema validation my dict should convert snake case type to camel case as below,
JavaScript
1
5
1
{
2
"titleName": "search001",
3
"statusType": "New"
4
}
5
How can I define a pydantic schema to achieve the above problem?
Thanks in advance.
Advertisement
Answer
You can use Alias Generator
JavaScript
1
22
22
1
from pydantic import BaseModel
2
3
4
def to_snake_case(string: str) -> str:
5
return ''.join(['_' + i.lower() if i.isupper() else i for i in string]).lstrip('_')
6
7
8
class MyModel(BaseModel):
9
titleName: str
10
statusType: str
11
12
class Config:
13
alias_generator = to_snake_case
14
15
16
data = {
17
"title_name": "search001",
18
"status_type": "New"
19
}
20
print(MyModel(**data).dict()) # {'titleName': 'search001', 'statusType': 'New'}
21
22