【问题标题】:How to create a custom sort order for the API methods in FastAPI Swagger autodocs?如何为 FastAPI Swagger 自动文档中的 API 方法创建自定义排序顺序?
【发布时间】:2022-08-19 01:42:26
【问题描述】:
我怎样才能设置一个风俗FastAPI Swagger autodocs 中 API 方法的排序顺序?
This question 展示了如何在 Java 中执行此操作。我的previous question 询问如何按“方法”排序,这是一种受支持的排序方法。我真的很想更进一步,这样我就可以确定方法出现的顺序。现在DELETE 出现在顶部,但我希望它按以下顺序排列:GET、POST、PUT、DELETE。
我知道可以在Javascript 中实现自定义排序并将该函数提供给operationsSorter,但是您不能从Python 绑定中可用的swagger_ui_parameters 属性中包含它。有什么方法可以在 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
标签:
python
swagger
swagger-ui
fastapi
openapi
【解决方案1】:
您可以使用 tags 对端点进行分组。为此,请将参数tags 与list 或str(通常只有一个str)一起传递到您的端点。对使用相同 HTTP 方法的端点使用相同的标记名称,以便您可以通过这种方式对端点进行分组。例如,使用Get 作为GET 操作的标签名称(注意:Get 只是一个示例名称,您可以使用您选择的标签名称)。
仅执行上述操作很可能会按照您希望的顺序定义端点(即GET、POST、PUT、DELETE)。然而,为了确保这一点——或者,即使你想为你的方法/标签定义不同的顺序——你可以add metadata for the different tags used to group your endpoints。您可以使用参数openapi_tags 做到这一点,该参数采用list,每个标签包含一个dictionary。每个字典至少应包含name,它应与tags 参数中使用的标记名称相同。 The order of each tag metadata dictionary also defines the order shown in the docs UI.
下面的工作示例:
from fastapi import FastAPI
tags_metadata = [
{"name": "Get"},
{"name": "Post"},
{"name": "Put"},
{"name": "Delete"}
]
app = FastAPI(openapi_tags=tags_metadata)
@app.get("/", tags=["Get"])
def list_all_components():
pass
@app.get("/{component_id}", tags=["Get"])
def get_component(component_id: int):
pass
@app.post("/", tags=["Post"])
def create_component():
pass
@app.put("/{component_id}", tags=["Put"])
def update_component(component_id: int):
pass
@app.delete("/{component_id}", tags=["Delete"])
def delete_component(component_id: int):
pass