如何在FastAPI中使用Swagger UI展示API文档

如何在FastAPI中使用Swagger UI展示API文档

导言:在现代Web开发中,API是不可或缺的一部分。为了方便开发和维护,我们需要提供一个友好且易于使用的API文档,以便其他开发人员可以了解和使用我们的API。Swagger是一种流行的API文档格式和工具,它提供了一个交互式的UI界面,可以直观地展示API的细节。在本文中,我将向您展示如何在FastAPI中使用Swagger UI来展示API文档。

    安装依赖首先,我们需要安装FastAPI和相关的依赖。可以使用以下命令进行安装:

    pip install fastapi[all]

    这将安装FastAPI及其所需的所有依赖项,包括Swagger UI。

    创建FastAPI应用接下来,我们将创建一个FastAPI应用。在一个新的Python文件中,编写以下代码:

    from fastapi import FastAPIapp = FastAPI()@app.get("/")async def root(): return {"message": "Hello World"}

    这个简单的应用定义了一个根路由,用于返回一个简单的“Hello World”消息。

    添加Swagger UI为了添加Swagger UI到我们的应用中,我们需要导入相关的FastAPI组件。将以下代码添加到我们的应用文件中:

    from fastapi import FastAPIfrom fastapi.openapi.utils import get_openapifrom fastapi.openapi.docs import get_swagger_ui_htmlapp = FastAPI()@app.get("/")async def root(): return {"message": "Hello World"}def custom_swagger_ui_html(*, request): openapi_url = app.openapi_url swagger_url = openapi_url.replace("/openapi.json", "/swagger") return get_swagger_ui_html(     openapi_url=openapi_url,     title=app.title + " - Swagger UI",     oauth2_redirect_url=swagger_url + "/oauth2-redirect.html",     swagger_js_url="/static/swagger-ui-bundle.js",     swagger_css_url="/static/swagger-ui.css", )app.openapi = get_openapi(title="My API")@app.get("/swagger", include_in_schema=False)async def swagger_ui_html(request: Request): return custom_swagger_ui_html(request=request)app.mount("/static", StaticFiles(directory="static"), name="static")

    在代码中,我们创建了一个名为custom_swagger_ui_html的自定义函数。这个函数将使用FastAPI提供的get_swagger_ui_html函数来生成Swagger UI的HTML页面。我们还为Swagger UI定义了一些URL和静态文件的路径。

    运行应用现在我们的应用已经准备就绪,可以运行它了。在终端中,使用以下命令来启动应用:

    uvicorn main:app --reload

    这将启动我们的应用,并使其运行在本地的默认地址http://localhost:8000上。

    查看API文档在浏览器中打开http://localhost:8000/swagger,你将看到一个交互式的Swagger UI界面。它将显示您的API的详细信息,包括路由、请求和响应模型等等。

结论:通过使用FastAPI和Swagger UI,我们可以轻松地展示和浏览我们的API文档。这使得开发人员可以更加方便地了解和使用我们的API。希望本文能对您在FastAPI中使用Swagger UI展示API文档有所帮助。

【本文转自:海外高防服务器 krgf.html 欢迎留下您的宝贵建议】穷则思变,差则思勤!没有比人更高的山没有比脚更长的路。

如何在FastAPI中使用Swagger UI展示API文档

相关文章:

你感兴趣的文章:

标签云: