DRF-YASG Swagger文档不识别授权用户且接口无参数字段显示
DRF-YASG Swagger认证与参数字段问题解决
核心问题有两个:一是Swagger UI无法识别已授权用户的Token认证状态,二是除手动配置的LoginView外,其他端点不展示参数字段输入框。以下是针对性解决步骤:
一、修复Swagger认证状态识别问题
drf-yasg默认未配置Token认证的Swagger支持,需手动添加安全方案,让Swagger能处理Authorization请求头:
修改urls.py中的schema_view配置:
from django.contrib import admin from django.urls import path, include, re_path from EmployeeApp import views from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi # 新增Token认证安全方案配置 token_auth = openapi.SecurityScheme( type="apiKey", name="Authorization", in_="header", description="认证格式:Token <你的令牌字符串>" ) schema_view = get_schema_view( openapi.Info( title="Snippets API", default_version='v1', description="Test description", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@snippets.local"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=[permissions.AllowAny], # 启用Token认证安全方案 security=[{'TokenAuth': []}], schemes=[token_auth], ) urlpatterns = [ re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('admin/', admin.site.urls), path('', views.api_home), path('api/', include('EmployeeApp.urls')), path('api/auth/', include('accounts.urls')), ]
配置完成后,Swagger UI右上角会出现「Authorize」按钮,输入Token <你的令牌>即可让后续请求自动携带认证头,Swagger也能识别当前认证状态。
二、修复端点参数字段不展示问题
APIView不会自动向drf-yasg暴露序列化器信息,需在视图的@swagger_auto_schema装饰器中显式指定request_body参数:
1. 修改CompanyCreate视图
from drf_yasg.utils import swagger_auto_schema from .serializers import CompanySerializer from rest_framework.permissions import IsAuthenticated class CompanyCreate(APIView): permission_classes = [IsAuthenticated] @swagger_auto_schema( operation_summary="Create a company", operation_description="This allows logged-in user to create a company", # 显式指定请求体的序列化器 request_body=CompanySerializer ) def post(self, request): company_name_exists = Companies.objects.filter(company_name=request.data['company_name']).exists() if company_name_exists: raise ValidationError("Company with the same name already exists") data = {**request.data, 'user_id': request.auth.user_id} serializer = CompanySerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
2. 补充SignUpView的装饰器(可选,确保字段展示)
class SignUpView(generics.GenericAPIView): serializer_class = SignUpSerializer @swagger_auto_schema(request_body=SignUpSerializer) def post(self, request: Request): data = request.data serializer = self.serializer_class(data=data) if serializer.is_valid(): serializer.save() response = { "message": "User Created Successfully", "data": serializer.data } return Response(data=response, status=status.HTTP_201_CREATED) return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
三、修复settings.py中的拼写错误
注意到REST_FRAMEWORK配置中DEFAULT_PERMISSON_CLASSES存在拼写错误,修正为DEFAULT_PERMISSION_CLASSES,否则默认权限规则可能不生效:
REST_FRAMEWORK = { "NON_FIELD_ERRORS_KEY": "errors", "DEFAULT_AUTHENTICATION_CLASSES":( "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication" ), # 修正拼写错误 "DEFAULT_PERMISSION_CLASSES":( "rest_framework.permissions.IsAuthenticated" ) }
完成以上修改后,重启服务即可看到:Swagger能识别认证状态,所有配置了request_body的端点都会展示对应的参数字段输入框。
内容的提问来源于stack exchange,提问作者pgun
相关产品推荐
相关产品推荐

