You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI Swagger API中如何按方法类型对接口排序

FastAPI Swagger接口按请求类型排序实现方案

直接通过FastAPI内置的Swagger UI配置参数即可实现接口按GET、POST、PUT、DELETE的请求类型分组排序,无需额外引入依赖或修改前端源码。

配置原理

Swagger UI原生提供operationsSorter配置项用于控制接口排序规则,FastAPI支持在实例化应用时通过swagger_ui_parameters参数透传所有Swagger UI原生配置。
operationsSorter支持的常用配置值:

  • "alpha":默认值,按接口路径的字母顺序排序
  • "method":按HTTP请求方法排序,默认顺序为GET > POST > PUT > DELETE > PATCH > OPTIONS > HEAD,可直接满足按请求类型分组展示的需求
  • 自定义函数:传入JS函数字符串即可实现完全自定义的排序逻辑

可直接运行的代码示例

修改FastAPI实例化代码,添加排序配置即可:

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

自定义排序顺序

如果需要调整请求方法的排序优先级,可以传入自定义JS函数固定排序规则,示例如下:

app = FastAPI(
    swagger_ui_parameters={
        "operationsSorter": """(a, b) => {
            const methodPriority = ['GET', 'POST', 'PUT', 'DELETE']
            return methodPriority.indexOf(a.get('method')) - methodPriority.indexOf(b.get('method'))
        }"""
    }
)

如果需要同时对接口分类标签排序,可额外添加"tagsSorter": "alpha"配置,实现标签按名称字母顺序排列。

效果展示

按请求类型分组排序后的Swagger文档界面

内容的提问来源于stack exchange,提问作者Salvatore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 21:06:28