Created
February 4, 2023 13:48
-
-
Save devxoul/87b5013a8690a84e1e4620079cfe17ae to your computer and use it in GitHub Desktop.
Camelize FastAPI path params and query params.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Camelize FastAPI path params and query params. | |
For body params and responses, use pydantic model's alias_generator config. | |
""" | |
from fastapi import FastAPI | |
from fastapi.dependencies.models import Dependant | |
from fastapi.routing import APIRoute | |
from humps import camelize | |
from starlette.routing import compile_path | |
def camelize_app( | |
app: FastAPI, | |
path_params: bool = True, | |
query_params: bool = True, | |
): | |
routes = [route for route in app.routes if isinstance(route, APIRoute)] | |
if path_params: | |
for route in routes: | |
_camelize_path_params(route.dependant) | |
_recompile_path(route) | |
if query_params: | |
for route in routes: | |
_camelize_query_params(route.dependant) | |
def _camelize_path_params(dependant: Dependant): | |
for param in dependant.path_params: | |
param.alias = camelize(param.name) | |
if dependant.path: | |
dependant.path = dependant.path.replace(f"{{{param.name}}}", f"{{{param.alias}}}") | |
for sub_dependant in dependant.dependencies: | |
_camelize_path_params(sub_dependant) | |
def _camelize_query_params(dependant: Dependant): | |
for param in dependant.query_params: | |
param.alias = camelize(param.name) | |
for sub_dependant in dependant.dependencies: | |
_camelize_query_params(sub_dependant) | |
def _recompile_path(route: APIRoute): | |
if not route.dependant.path: | |
return | |
route.path = route.dependant.path | |
route.path_regex, route.path_format, route.param_convertors = compile_path(route.path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment