You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FastAPI文档描述中添加Mermaid流程图?

在FastAPI文档中添加Mermaid流程图的简便方法

FastAPI默认会对文档描述中的HTML内容做清理,移除script标签和自定义类,所以直接在description里嵌入Mermaid相关代码的方式行不通。这里提供一种无需额外静态资源、仅通过配置FastAPI即可实现的方案:

实现步骤

通过FastAPI的swagger_ui_parameters参数注入自定义JavaScript,自动加载Mermaid并渲染文档中的Mermaid代码块:

from fastapi import FastAPI

description = """
### 系统架构示例
```mermaid
graph TD 
A[Client] --> B[Load Balancer] 
B --> C[Server01] 
B --> D[Server02]

"""

app = FastAPI(
description=description,
swagger_ui_parameters={
"custom_js": """
// 动态加载Mermaid脚本
const mermaidScript = document.createElement('script');
mermaidScript.src = 'https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js';
mermaidScript.onload = function() {
// 初始化Mermaid
mermaid.initialize({ startOnLoad: true });
// 遍历所有mermaid代码块,替换为Mermaid渲染容器
document.querySelectorAll('pre code.language-mermaid').forEach(block => {
const container = document.createElement('div');
container.className = 'mermaid';
container.textContent = block.textContent;
block.parentElement.replaceWith(container);
});
};
document.head.appendChild(mermaidScript);
"""
}
)

### 原理说明
1. 先在文档描述中用标准的代码块语法(```mermaid```)编写Mermaid流程图代码,FastAPI不会过滤这种格式的内容。
2. 通过`swagger_ui_parameters`的`custom_js`注入脚本:
   - 动态创建并加载Mermaid的CDN脚本
   - 脚本加载完成后初始化Mermaid
   - 自动识别页面中所有标记为`language-mermaid`的代码块,将其替换为Mermaid的渲染容器,最终由Mermaid自动生成流程图

内容的提问来源于stack exchange,提问作者Madaray
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:11:29