Is it possible to apply alias generator from pydantic to FastApi fields?
See original GitHub issueFirst Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
from fastapi import Body, Query
from pydantic import BaseConfig, BaseModel, Field
def to_camelcase(string: str) -> str:
res = ''.join(word.capitalize() for word in string.split('_'))
return res[0].lower() + res[1:]
class User(BaseModel):
class Config(BaseConfig):
alias_generator = to_camelcase
allow_population_by_field_name = True
first_name: str = Field()
last_name: str = Field()
@app.post('/user')
def create_user(
user: User = Body(...),
send_invite: bool = Query(...),
):
...
Description
On backend we’re using FastApi and native to python snake_case
notation, however, on frontend - there is a JS with their camelCase
notation.
In the code above, client can submit body with either snake or camel case and pydantic will do the magic to understand it. However, for the query parameter it doesn’t work this way: send_invite
is expected to be in snake case only. So this would be a violation of the overall structure either on the UI (they’d have to use snake for query and camel for body) or in the api (snake for everything, but camel for the query).
Thus, i wonder, what would be the best way to work this around?
Operating System
Other
Operating System Details
Not applicable (doesn’t matter)
FastAPI Version
0.65.2
Python Version
3.9
Additional Context
Pydantic version: 1.8.2
Issue Analytics
- State:
- Created 2 years ago
- Comments:11 (1 by maintainers)
Top Results From Across the Web
return pydantic model with field names instead of alias as ...
I know it's somewhat possible when using the dict method of the model, but it doesn't feel right and messes up the typing...
Read more >Body - Fields - FastAPI
You can use Pydantic's Field to declare extra validations and metadata for model attributes. You can also use the extra keyword arguments to...
Read more >CamelCase Models with FastAPI and Pydantic - Medium
We can generate aliases for all of the model fields as follows: from pydantic import BaseModel from humps import camelize
Read more >datamodel-code-generator - GitHub Pages
This code generator creates pydantic model from an openapi file and others. ... [--original-field-name-delimiter ORIGINAL_FIELD_NAME_DELIMITER] ...
Read more >Settings management - pydantic
Create a clearly-defined, type-hinted application configuration class ... Note 2: Field aliases are ignored when building the environment variable name.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I’ve studied on this for a while, there are several workarounds, but all not perfect. I’m going to write a pr to provide a perfect solution to it.
I’m going to share some of the workarounds here:
polyfill
alias_generator
with a decorator
Since we also need to modify the generated schema, dependency is not useful here. I use a decorator to update the
alias
attribute ofQuery
andPath
. Maybe some more types of Param can be updated as well.I use the
makefun
module to modify the signature of the function. I use thesnake2camel
from thefastapi_utils
module, you can use any function to generate the alias you prefer.Add the
camelcase_parameters
decorator between the@router.xxx
and the route function definition. Now allQuery
andPath
without alias will have a generated one (the camalCase of the original name).monkey patch
fastapi
dependencyAnother solution is to modify
fastapi
itself infastapi/dependencies/utils.py
. The functions in this file are mainly for parsing the dependencies. We can modify a functionget_param_field
.On this line
https://github.com/tiangolo/fastapi/blob/58ab733f19846b4875c5b79bfb1f4d1cb7f4823f/fastapi/dependencies/utils.py#L381
We can find that
alias
is set fromparam.name
iffield_info.alias
is not provided. If we change it intoNow a generated alias with snake2camel is set.
The complete version of the patch is
You should put these lines before importing your apis (or using any dependency). In my project, I put it the first line in the file with
app = FastAPI(...)
.However, this method is quite dirty. You have to fix to a
fastapi
release because if the function is modifed in a future release, it may introduce bad behaviors.I would love a FastAPI app wide
alias_generator
type functionality, to be applied to e.g. Query and Path parameters. Currently I am manually defining camelCase aliases for all Path and Query parameters in my app.