fastapiopenapiopenapi-generator

Change default naming-behavior for operation_id


If I generate a Java client based on the following endpoint:

api_users = APIRouter(prefix='/api/users', tags=['users'])


class User(BaseModel):
    name: str


@api_users.get(
    path='',
    response_model=List[User],
)
async def get_users():
    return [User(name='test')]

The method name inside the UserApi.java file for it will be getUsersApiUsersGet() instead of getUsers(). I have to set the operation_id to something like get_users as in

@api_users.get(
    path='',
    response_model=List[User],
    operation_id='get_users'
)

but this is tedious. Why isn't it just grabbing the method name itself, and uses this as default value instead?

So, is there a way I can change that behavior?


Solution

  • It's a bit weird that this is not standard behavior but we can achieve this by running this:

    def use_route_names_as_operation_ids(application: FastAPI) -> None:
        """
        Simplify operation IDs so that generated API clients have simpler function
        names.
    
        Should be called only after all routes have been added.
        """
        for route in application.routes:
            if isinstance(route, APIRoute):
                route: APIRoute = route
                route.operation_id = route.name
    
    
    app = FastAPI()
    controller.initialize(app)
    use_route_names_as_operation_ids(app)  # Call after controller were initialized