如何为FastAPI Swagger自动文档的API方法设置自定义排序顺序
如何为FastAPI Swagger自动文档中的API方法设置自定义排序顺序
目前已知内置的operationsSorter: "method"配置可以按HTTP请求方法对接口排序,但默认排序规则下DELETE方法会显示在最顶部,无法满足按GET→POST→PUT→DELETE固定顺序展示的需求。
原生Swagger UI支持传入自定义JavaScript函数给operationsSorter配置项实现自定义排序,但FastAPI提供的swagger_ui_parameters参数默认不支持直接传入JS函数,以下是纯Python层面的实现方案,不需要额外托管前端静态文件。
默认配置下的示例代码:
from fastapi import FastAPI app = FastAPI(swagger_ui_parameters={"operationsSorter": "method"}) @app.get("/") def list_all_components(): pass @app.get("/{component_id}") def get_component(component_id: int): pass @app.post("/") def create_component(): pass @app.put("/{component_id}") def update_component(component_id: int): pass @app.delete("/{component_id}") def delete_component(component_id: int): pass
默认排序效果:
实现方法
通过覆写FastAPI默认的/docs路由,在Python代码中直接注入自定义排序的JS逻辑即可,全程不需要修改前端文件:
from fastapi import FastAPI from fastapi.openapi.docs import get_swagger_ui_html from fastapi.responses import HTMLResponse import json app = FastAPI() # 自定义HTTP方法排序优先级,数值越小展示位置越靠前 METHOD_PRIORITY = { "GET": 0, "POST": 1, "PUT": 2, "DELETE": 3 } # 覆写默认文档路由,注入自定义排序逻辑 @app.get("/docs", include_in_schema=False) async def custom_swagger_docs(): # 自定义JS标记,用于后续序列化替换 js_marker = "__CUSTOM_JS_SORTER__" # 构造自定义排序函数 sorter_function = f"""{js_marker} (a, b) => {{ const priorityMap = {json.dumps(METHOD_PRIORITY)}; const methodSort = priorityMap[a.get("method")] - priorityMap[b.get("method")]; // 相同请求方法下按路径字典序排序,不需要可以删除后半段逻辑 return methodSort !== 0 ? methodSort : a.get("path").localeCompare(b.get("path")); }} """ html_response = get_swagger_ui_html( openapi_url=app.openapi_url, title=f"{app.title} - Swagger UI", swagger_ui_parameters={ "operationsSorter": sorter_function } ) # 替换序列化后的字符串标记,转为原生JS函数 html_content = html_response.body.decode("utf-8") html_content = html_content.replace(f'"{js_marker}', "").replace(f'{js_marker}"', "") return HTMLResponse(content=html_content, status_code=200) # 业务接口示例 @app.get("/") def list_all_components(): pass @app.get("/{component_id}") def get_component(component_id: int): pass @app.post("/") def create_component(): pass @app.put("/{component_id}") def update_component(component_id: int): pass @app.delete("/{component_id}") def delete_component(component_id: int): pass
使用说明
- 调整
METHOD_PRIORITY字典的键值即可自定义排序规则,如需新增PATCH等方法,直接在字典中添加对应优先级数值即可 - 如果不需要同方法下按路径排序,直接将排序函数返回值改为
return priorityMap[a.get("method")] - priorityMap[b.get("method")]即可 - 方案完全基于Python原生能力实现,不需要编写、引入额外的前端静态资源文件
内容的提问来源于stack exchange,提问作者Salvatore
相关产品推荐
相关产品推荐

