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.
Lets assume that you have an endpoint representing a user
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 POST
requests to create a user
@app.post("/user/create", response_model=User)
async def create_user(user: User):
return user
if we look at /docs
we will see that our schema is in snake_case as expected
fixing that is really easy with fastapi-camelcase
package
Installation
pip install fastapi_camelcase
edit your code as follows
instead of from pydantic import BaseModel
we will use from fastapi_camelcase import CamelModel
and we will use CamelModel
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!