Django REST API手动添加Swagger文档后响应示例值无法加载
问题解决:DRF-YASG手动定义的响应示例无法加载
问题分析
非模型关联的Verification视图通过swagger_auto_schema手动编写Swagger文档后,Responses部分的示例值一直处于加载转圈状态,依赖模型/序列化器的API文档生成正常,且已安装最新版drf-yasg。
修复方案
方案1:规范响应示例定义格式
drf-yasg中openapi.Response的examples参数需要使用openapi.Examples和openapi.Example对象规范定义,而非直接传入字典。修改代码如下:
from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import status class Verification(APIView): @swagger_auto_schema( request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'phone': openapi.Schema(type=openapi.TYPE_STRING, description='Phone number to verify'), 'token': openapi.Schema(type=openapi.TYPE_STRING, description='Verification token sent via SMS') }, required=['phone', 'token'] ), responses={ 200: openapi.Response( description='Successful verification', examples=openapi.Examples( value={ 'application/json': openapi.Example( name='成功验证示例', value={'status': True, 'detail': '200, your entered token matched.'} ) } ) ), 400: openapi.Response( description='Invalid input or verification failed', examples=openapi.Examples( value={ 'application/json': openapi.Example( name='验证失败示例', value={'status': False, 'detail': 'entered token is NOT true'} ) } ) ) } ) def post(self, request): number = request.data.get('phone') sent_tok = request.data.get('token') if number and sent_tok: old = Customer.objects.filter(phone__iexact=number) if old.exists(): old = old.first() saved_tok = old.sms_token if str(sent_tok) == str(saved_tok): old.is_verified = True old.save() return Response({ 'status': True, 'detail': '200, your entered token matched.' }) else: return Response({ 'status': False, 'detail': 'entered token is NOT true' }, status=status.HTTP_400_BAD_REQUEST) # 补充缺失的参数校验返回逻辑 return Response({ 'status': False, 'detail': 'Phone number or token is missing' }, status=status.HTTP_400_BAD_REQUEST)
方案2:结合Schema与Example定义
若方案1无效,可同时定义响应的Schema结构和示例值,帮助Swagger UI正确识别渲染:
responses={ 200: openapi.Response( description='Successful verification', schema=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'status': openapi.Schema(type=openapi.TYPE_BOOLEAN, description='Verification status'), 'detail': openapi.Schema(type=openapi.TYPE_STRING, description='Verification result detail') } ), examples={ 'application/json': {'status': True, 'detail': '200, your entered token matched.'} } ), 400: openapi.Response( description='Invalid input or verification failed', schema=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'status': openapi.Schema(type=openapi.TYPE_BOOLEAN, description='Verification status'), 'detail': openapi.Schema(type=openapi.TYPE_STRING, description='Verification result detail') } ), examples={ 'application/json': {'status': False, 'detail': 'entered token is NOT true'} } ) }
额外注意事项
- 补充视图缺失的响应逻辑:原代码中当
phone或token为空时无返回,会导致请求异常,也可能干扰Swagger渲染; - 清除浏览器缓存:修改代码后强制刷新页面(Ctrl+F5),避免Swagger UI加载旧缓存文档。
内容的提问来源于stack exchange,提问作者MohsenNS
相关产品推荐
相关产品推荐

