Mat*_*one 8 python swagger swagger-ui openapi fastapi
如何在FastAPI Swagger autodocs中为 API 方法设置自定义排序顺序?
这个问题展示了如何在 Java 中做到这一点。我之前的问题询问如何按“方法”排序,这是受支持的排序方法。我真的很想更进一步,以便我可以确定方法出现的顺序。现在DELETE显示在顶部,但我希望 API 方法的顺序为:GET, POST, PUT, DELETE。
我知道可以在 JavaScript 中实现自定义排序并将该函数提供给operationsSorter,但您不能从swagger_ui_parametersPython 绑定中可用的属性中包含它。有什么方法可以在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
Run Code Online (Sandbox Code Playgroud)
您可以使用tags对端点进行分组。为此,请将tags带有listof str(通常只有 1 str)的参数传递到您的端点。name对使用相同方法的端点使用相同的标签HTTP,以便您可以按这种方式对端点进行分组。例如,用作操作Get的标签名称GET(注意:Get这里只是一个示例,您可以使用任何name您想要的标签)。
仅执行上述操作很可能会按照您希望的顺序定义端点(即,GET, POST, PUT, DELETE)。但是,为了确保这一点,即使您想为方法/标签定义不同的顺序,您也可以为用于对端点进行分组的不同标签添加元数据。您可以使用参数 来做到这一点openapi_tags,该参数为每个标签都list包含一个参数dictionary。每个字典至少应该包含name,它应该与参数name中使用的标签相同tags。每个标签元数据字典的顺序也定义了文档 UI 中显示的顺序。
from fastapi import FastAPI\n\ntags_metadata = [\n {"name": "Get"},\n {"name": "Post"},\n {"name": "Put"},\n {"name": "Delete"}\n]\n\napp = FastAPI(openapi_tags=tags_metadata)\n\n@app.get("/", tags=["Get"])\ndef list_all_components():\n pass\n\n@app.get("/{component_id}", tags=["Get"])\ndef get_component(component_id: int):\n pass\n\n@app.post("/", tags=["Post"])\ndef create_component():\n pass\n\n@app.put("/{component_id}", tags=["Put"])\ndef update_component(component_id: int):\n pass\n\n@app.delete("/{component_id}", tags=["Delete"])\ndef delete_component(component_id: int):\n pass\nRun Code Online (Sandbox Code Playgroud)\n