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

drf-yasg生成Swagger文档时URL缺失api/前缀问题求助

解决drf-yasg生成Swagger接口文档缺失api/前缀的问题

问题原因

drf-yasg默认根据视图的相对路径生成接口URL,你的schema_view未挂载到api/前缀下,导致无法识别全局的api/路径前缀,所以生成的接口URL都缺失了该前缀。

解决方案

提供三种可行的处理方式:

方式1:将Swagger相关路由迁移到api/前缀下

修改urlpatterns,把Swagger的路由都放到api/路径下,让schema_view以api/为基准路径解析接口:

urlpatterns = [
    # 调整Swagger路由到api/前缀下
    path('api/swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    url(r'^api/swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    url(r'^api/redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),

    path('api/', include(router.urls)),
    path('api/search-options', SearchPlacesOptionsView.as_view()),
]

方式2:通过urlconf指定全局路由配置

在get_schema_view中添加urlconf参数,指向你的项目全局路由模块,让drf-yasg完整解析路由结构:

schema_view = get_schema_view(
    openapi.Info(
        title="My API",
        default_version='v1',
        description="...",
        terms_of_service="你的服务条款链接",
        contact=openapi.Contact(email="hello@mycompany.com"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=[permissions.AllowAny],
    urlconf='你的项目名称.urls'  # 替换为实际的项目urls模块路径,比如myproject.urls
)

方式3:手动设置base_path强制添加前缀

直接在get_schema_view中指定base_path参数,强制所有接口URL带上api/前缀:

schema_view = get_schema_view(
    openapi.Info(
        title="My API",
        default_version='v1',
        description="...",
        terms_of_service="你的服务条款链接",
        contact=openapi.Contact(email="hello@mycompany.com"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=[permissions.AllowAny],
    base_path='api/'
)

验证

修改完成后重启服务,重新访问Swagger页面,就能看到所有接口URL都已包含api/前缀。

内容的提问来源于stack exchange,提问作者Saleh Rabbaniy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 21:50:39