如何在Django Rest Framework中为/api路径配置可浏览API根页面
给/api层级添加可浏览API页面的解决方案
要实现访问/api时显示可浏览的API页面,直接跳转至/api/v1和/api/schema,只需在my_api_app/router.py中添加一个根视图,利用DRF的可浏览API渲染器生成页面即可,具体步骤如下:
1. 修改django_project/my_api_app/router.py
在该文件中新增根视图类,并将其映射到/api的根路径:
from django.urls import include, path from rest_framework import routers from rest_framework.schemas import get_schema_view from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.reverse import reverse from .v1.router import router as v1_router # 新增根视图,返回v1 API和schema的跳转链接 class RootAPIView(APIView): def get(self, request, format=None): return Response({ 'v1 API入口': reverse('api:v1-testtable-list', request=request, format=format), 'API Schema文档': reverse('api:openapi-schema', request=request, format=format) }) urlpatterns = [ path('', RootAPIView.as_view(), name='api-root'), # 绑定到/api根路径 path('schema', get_schema_view( title="Python API", description="API for all things", version="1.0.0", public=True ), name='openapi-schema'), path('v1/', include(v1_router.urls)), path('api-auth/', include('rest_framework.urls')), ]
2. 关键说明
- 新增的
RootAPIView继承自DRF的APIView,get方法返回包含跳转链接的字典,DRF会自动将其渲染为可浏览的API页面。 reverse函数生成URL时,使用了config/urls.py中api/路由的命名空间api,v1-testtable-list是DefaultRouter为testtable视图集自动生成的列表页路由名称。- 绑定空路径
path('', ...)后,访问/api即可看到带跳转链接的可浏览页面,点击链接直接进入对应功能页。
现有配置参考
django_project/config/urls.py
from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from rest_framework import generics from rest_framework.response import Response from rest_framework.reverse import reverse urlpatterns = [ path('api/', include('my_api_app.router'), name="api"), path('admin/', admin.site.urls), ]
django_project/my_api_app/v1/router.py
from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'testtable', views.TestTableViewSet)
内容的提问来源于stack exchange,提问作者Ewro
相关产品推荐
相关产品推荐

