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

Django REST API文档报错:openapi-schema未找到,求自动生成方案

解决Django REST API Swagger文档生成的报错问题

首先,你遇到的Reverse for 'openapi-schema' not found报错,核心原因是你的项目里没有配置对应openapi-schema的URL路由——Swagger UI需要这个路由来获取API的结构化描述信息,但你目前的urls.py里完全没定义这个路径,所以Django找不到它。

下面是具体的解决步骤,以及对你疑问的解答:

一、先搞定报错:添加openapi-schema路由

要自动生成OpenAPI schema,我们可以用drf-yasg这个专门为Django REST Framework设计的库,它能自动从你的API视图、序列化器生成schema,不需要手动写文件。

1. 安装依赖

先在虚拟环境里安装包:

pip install drf-yasg

2. 更新urls.py配置

修改你的urls.py,添加schema生成的路由,同时调整现有配置:

from django.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic.base import TemplateView
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

# 生成schema视图,可自定义API的基础信息
schema_view = get_schema_view(
   openapi.Info(
      title="你的项目API名称",
      default_version='v1',
      description="你的API功能描述",
      terms_of_service="https://your-domain.com/terms",
      contact=openapi.Contact(email="your-contact@example.com"),
      license=openapi.License(name="MIT License"),
   ),
   public=True,
   permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
    path('api/', include('api.urls')),
    path('admin/', admin.site.urls),
    path('', include('main.urls')),
    # 添加openapi-schema的路由,对应模板里的schema_url参数
    path('openapi-schema/', schema_view.without_ui(cache_timeout=0), name='openapi-schema'),
    path('swagger-ui/', TemplateView.as_view(
        template_name='swagger-ui.html',
        extra_context={'schema_url': 'openapi-schema'}
    ), name='swagger-ui'),
    # 通配路由放在最后,避免覆盖其他有效路由
    re_path(r'^.*', TemplateView.as_view(template_name="home.html")),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

这样,openapi-schema就成为了一个有效的Django路由名称,模板里的{% url schema_url %}就能正确解析了。

二、解答你的三个疑问

  • openapi-schema文件应放置在何处?
    不需要手动创建或放置任何文件!openapi-schema是一个由drf-yasg自动生成的HTTP接口,当访问/openapi-schema/时,它会动态返回符合OpenAPI规范的JSON格式数据,Swagger UI就是通过这个接口获取API文档的结构信息的。

  • 它是.yml文件还是.js文件?
    自动生成的是JSON格式的响应,不过drf-yasg也支持生成YAML格式(比如通过schema_view.with_ui('swagger', cache_timeout=0)视图)。你完全不需要手动写.yml或.js文件,一切都是自动生成的。

  • 是否可以自动生成该文件?
    当然可以!用drf-yasg或者另一个流行的库drf-spectacular,都能根据你写的Django REST Framework视图、序列化器自动生成完整的OpenAPI schema,包括接口路径、请求参数、响应格式等信息,不需要手动维护。

另外,如果你不想自己维护swagger-ui.html模板,drf-yasg还提供了自带的Swagger UI和ReDoc视图,直接在urls.py里添加如下路由就能使用:

path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),

这样连自定义模板都省了,直接访问/swagger/就能看到自动生成的文档。

内容的提问来源于stack exchange,提问作者Aigerim Sadir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 23:02:52