When I specify the API and schema in FastAPI (OpenAPI) and let FastAPI generate the schema objects/classes, the member names are formatted snake case and get a alias name in camel case.
class ObjectIdentifier(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
ObjectIdentifier - a model defined in OpenAPI
location: The location of this ObjectIdentifier.
location_type: The location_type of this ObjectIdentifier.
"""
location: str = Field(alias="location")
location_type: str = Field(alias="locationType")
ObjectIdentifier.update_forward_refs()
But when I populate a Pydantic class using its constructor and a dictionary from a database result set, the dictionary needs to contain the keys (attribute names) written with camel case.
# code that works
object_info = ObjectInformation(
objectId=ObjectIdentifier(location=location, locationType=location_type),
objectInfo=object_info
)
# code that does not work
object_info = ObjectInformation(
object_id=ObjectIdentifier(location=location, location_type=location_type),
object_info=object_info
)
Can I make the generated Pydantic code use snake case attribte names?
I tried several approaches using alias_generators
and the Config
object within a custom base class, but I can not use these approaches, as the Pydantic code is generated and I did not yet figure out how to use them in my context.
Ideally, I can use a syntax like this:
object_info = ObjectInformation(**database_result)
with database_result
like this:
database_result = dict(
location: "some location",
location_type: "some location type",
object_info: "the important object info"
)
That dictionary is a result of a query to a SQL DB, I can not get camel case attribute names as the DB access converts every name to lowercase. Thus, I can only get snake case from the DB results.
Notice, that the Pydantic structure is nested, ObjectIdentifier
inside ObjectInformation
. I dont know if nesting should work like I tried it.
Python: 3.9
Pydantic: 3.10.15