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

FastAPI配置Swagger requestInterceptor报错求助

解决FastAPI Swagger UI requestInterceptor报错问题

错误原因

你传入的requestInterceptor是字符串格式,但Swagger UI期望接收的是一个JavaScript函数。FastAPI的swagger_ui_parameters会将配置序列化为JSON传递给Swagger UI,JSON无法将字符串解析为函数,因此触发s.requestInterceptor is not a function错误。

解决方案

需要自定义Swagger UI的HTML模板,直接在模板中编写requestInterceptor函数逻辑,而非通过参数传递字符串。具体实现代码如下:

from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html

# 禁用默认的/docs路由,后续自定义实现
app = FastAPI(docs_url=None)

@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=f"{app.title} - Swagger UI",
        swagger_js_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js",
        swagger_css_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css",
        # 保留原有需要的配置项
        swagger_ui_parameters={
            "requestSnippetsEnabled": True,
            "persistAuthorization": True,
        },
        # 添加自定义脚本,直接初始化Swagger UI并配置requestInterceptor
        extra_head='''
        <script>
        window.onload = function() {
            const ui = SwaggerUIBundle({
                url: 'openapi.json',
                dom_id: '#swagger-ui',
                deepLinking: true,
                presets: [
                    SwaggerUIBundle.presets.apis,
                    SwaggerUIStandalonePreset
                ],
                plugins: [
                    SwaggerUIBundle.plugins.DownloadUrl
                ],
                layout: "StandaloneLayout",
                requestSnippetsEnabled: true,
                persistAuthorization: true,
                // 这里直接定义requestInterceptor函数
                requestInterceptor: (req) => {
                    req.headers['Authorization'] = 'Bearer <your_access_token>';
                    return req;
                }
            });
            window.ui = ui;
        };
        </script>
        '''
    )

代码说明

  1. 先禁用FastAPI默认的/docs路由,避免与自定义路由冲突
  2. 通过get_swagger_ui_html生成自定义Swagger UI页面,在extra_head中插入初始化脚本
  3. 在脚本中直接配置requestInterceptor为JavaScript函数,确保Swagger UI能正确识别并执行拦截逻辑

内容的提问来源于stack exchange,提问作者Ankit Bijlwan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 02:07:18