FastAPI and Pydantic CamelCase

Hassle free what to implement camelCase response/request body while keeping your python models pythonic and in snake_case.

I previously wrote an article about how to have a camelcase request response bodies while still having your python code in snake_case. Afterwards it made more sense to create a package and add it to PYPI.

PYPI

Github

Lets assume that you have an endpoint representing a resource as follows.

import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel

class User(BaseModel):
first_name: str
last_name: str
age: int


app = FastAPI()


@app.get("/user/get", response_model=User)
async def get_user():
return User(first_name="John", last_name="Doe", age=30)

if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)

Here was have our model or schema

class User(BaseModel):
first_name: str
last_name: str
age: int

and we have an endpoint which handles requests to create a user

@app.post("/user/create", response_model=User)
async def create_user(user: User):
return user

if we look at we will see that our schema is in snake_case as expected

fixing that is really easy with package

Installation

edit your code as follows

instead of we will use

and we will use whenever we need the request/response body to be camelCased.

class User(CamelModel):
first_name: str
last_name: str
age: int

Full code should look like this:

import uvicorn
from fastapi import FastAPI
from fastapi_camelcase import CamelModel


class User(CamelModel):
first_name: str
last_name: str
age: int


app = FastAPI()


@app.post("/user/create", response_model=User)
async def create_user(user: User):
return user


if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)

And Voilaaa!

Software Developer