更改 operation_id 的默认命名行为
Change default naming-behavior for operation_id
如果我根据以下端点生成 Java 客户端:
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')]
UserApi.java
文件中的方法名称将是 getUsersApiUsersGet()
而不是 getUsers()
。我必须将 operation_id
设置为 get_users
之类的东西,如
@api_users.get(
path='',
response_model=List[User],
operation_id='get_users'
)
但这很乏味。为什么它不直接获取方法名称本身,而是将其用作默认值?
那么,有什么方法可以改变这种行为吗?
这不是标准行为,这有点奇怪,但我们可以通过 运行 实现:
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
如果我根据以下端点生成 Java 客户端:
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')]
UserApi.java
文件中的方法名称将是 getUsersApiUsersGet()
而不是 getUsers()
。我必须将 operation_id
设置为 get_users
之类的东西,如
@api_users.get(
path='',
response_model=List[User],
operation_id='get_users'
)
但这很乏味。为什么它不直接获取方法名称本身,而是将其用作默认值?
那么,有什么方法可以改变这种行为吗?
这不是标准行为,这有点奇怪,但我们可以通过 运行 实现:
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