Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pydantic base model to parse and return camelCase JSON #17

Open
IrrerPolterer opened this issue Feb 21, 2023 · 2 comments
Open

Pydantic base model to parse and return camelCase JSON #17

IrrerPolterer opened this issue Feb 21, 2023 · 2 comments

Comments

@IrrerPolterer
Copy link

IrrerPolterer commented Feb 21, 2023

Credit: This idea has been inspired by this article and and this comment.

I want to be able to both...

  • parse incoming JSON with camelCase naming style, and
  • return camelCase JSON in my responses

For this I'm using a custom base model for pretty much all my Pydantic schemas:

from humps import camelize
from pydantic import BaseModel

class BaseSchema(BaseModel):
    class Config:
        # enable sqlalchemy model parsing
        orm_mode = True

        # enable camelCase JSON parsing
        alias_generator = camelize
        allow_population_by_field_name = True

    # enable camelCase json response
    def json(self, *args, **kwargs):
        kwargs.setdefault("by_alias", True)
        return super().json(*args, **kwargs)

(This requires the pyHumps package.)


With this BaseSchema, I can now create pydantic schemas with the intended behavior:

class Device(BaseSchema):
    name: str | None
    serial_number: str

# ingest camelCase
device = Device.parse_raw("""{"name": "Device XYZ", "serialNumber": "XYZ-123-ABC-000"}""")

# return camelCase
print(device.json())
# {"name": "Device XYZ", "serialNumber": "XYZ-123-ABC-000"}

My solution above uses the camelize function from the pyhumps package. Alternatively, you can create the function yourself like this:

def camelize(string: str) -> str:
    string_split = string.split("_")
    return string_split[0] + "".join(word.capitalize() for word in string_split[1:])
@IrrerPolterer IrrerPolterer changed the title Pydantic base model to parse and dump camelCase JSON, but works with snake_case python code Pydantic base model to parse and dump camelCase JSON Feb 21, 2023
@IrrerPolterer IrrerPolterer changed the title Pydantic base model to parse and dump camelCase JSON Pydantic base model to parse and return camelCase JSON Feb 21, 2023
@zhanymkanov
Copy link
Owner

Hey,

That's the good one! We do the same within our projects 💯

I didn't include it in the list since not every project needs camelCase, but this issue could be a good reference for those who do 👍

@copdips
Copy link

copdips commented Apr 1, 2024

the new version of Pydantic includes all of these built-in, no need to install humps anymore:

from pydantic import BaseModel
from pydantic.alias_generators import to_camel

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants