如何使用fastapi进行自定义doc文档

本文介绍了如何在使用FastAPI时,按照官方教程自定义文档界面,通过将SwaggerUI和Redoc的JavaScript和CSS文件下载到本地,并在启动文件中配置,使localhost:8000/docs显示定制化的文档界面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考官方文档地址:https://fastapi.tiangolo.com/zh/how-to/custom-docs-ui-assets/#self-hosting-javascript-and-css-for-docs

在使用fastapi的时候,按照官网的教程,访问localhost:8000/docs的时候,基本上是空白一片,在这个背景下,我们需要寻求帮助,以下内容就是我按照官网的文档进行整理的解决方案

版本介绍

python==3.9
fastapi==0.104.1

原项目目录:

.
├── app
│   ├── __init__.py
│   ├── main.py

改变后的项目目录

.
├── app
│   ├── __init__.py
│   ├── main.py
└── static
	├── redoc.standalone.js
	├── swagger-ui-bundle.js
	└── swagger-ui.css
三个文件的下载地址分别为:
  1. https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js
  2. https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css
  3. https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js
    如无法下载,可参考项目https://github.com/silk-java/fastapi-tutorial

在项目的启动文件中,添加如下代码


# ========设置docs文档为本地文件=========
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import (
    get_redoc_html,
    get_swagger_ui_html,
    get_swagger_ui_oauth2_redirect_html,
)
app.mount("/static", StaticFiles(directory="static"), name="static")

@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=app.title + " - Swagger UI",
        oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
        swagger_js_url="/static/swagger-ui-bundle.js",
        swagger_css_url="/static/swagger-ui.css",
    )

@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
    return get_swagger_ui_oauth2_redirect_html()

@app.get("/redoc", include_in_schema=False)
async def redoc_html():
    return get_redoc_html(
        openapi_url=app.openapi_url,
        title=app.title + " - ReDoc",
        redoc_js_url="/static/redoc.standalone.js",
    )
# ========设置docs文档为本地文件=========
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

micro_cloud_fly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值