如何在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 FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"}这个简单的应用定义了一个根路由,用于返回一个简单的“Hello World”消息。
-
添加Swagger UI
为了添加Swagger UI到我们的应用中,我们需要导入相关的FastAPI组件。将以下代码添加到我们的应用文件中:
Android 开发者指南 第一部分:入门下载Android文档-开发者指南-第一部分:入门-中英文对照版 Android提供了丰富的应用程序框架,它允许您在Java语言环境中构建移动设备的创新应用程序和游戏。在左侧导航中列出的文档提供了有关如何使用Android的各种API来构建应用程序的详细信息。第一部分:Introduction(入门) 0、Introduction to Android(引进到Android) 1、Application Fundamentals(应用程序基础) 2、Device Compatibility(设备兼容性) 3、
from fastapi import FastAPI from fastapi.openapi.utils import get_openapi from fastapi.openapi.docs import get_swagger_ui_html app = 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文档有所帮助。
以上就是如何在fastapi中使用swagger ui展示api文档的指南。希望本文能对您有所帮助。谢谢阅读!









