如何在drf-spectacular中设置POST请求默认内容类型为form-urlencoded
解决drf-spectacular中设置POST默认内容类型为application/x-www-form-urlencoded的方案
你之前的配置格式有误,OpenApiRequestBody需要正确定义请求体结构并指定默认内容类型。以下是两种可行的实现方式:
方式一:用序列化器定义请求体
先导入所需工具类,定义对应表单字段的序列化器,再在装饰器中配置:
from rest_framework import serializers from drf_spectacular.utils import extend_schema, OpenApiRequestBody # 定义登录请求的序列化器 class LoginSerializer(serializers.Serializer): email = serializers.EmailField(required=True) password = serializers.CharField(required=True) # 在视图上应用装饰器 @extend_schema( description='API authentication using email & password', request=OpenApiRequestBody( # 指定支持的内容类型及对应schema content={ 'application/x-www-form-urlencoded': { 'schema': LoginSerializer } }, # 设置默认选中的内容类型 default_content_type='application/x-www-form-urlencoded' ) ) def login_view(request): # 视图逻辑...
方式二:手动定义Schema(无需序列化器)
如果不想依赖序列化器,可直接在content中编写OpenAPI规范的schema:
from drf_spectacular.utils import extend_schema, OpenApiRequestBody @extend_schema( description='API authentication using email & password', request=OpenApiRequestBody( content={ 'application/x-www-form-urlencoded': { 'schema': { 'type': 'object', 'properties': { 'email': {'type': 'string', 'format': 'email'}, 'password': {'type': 'string'} }, 'required': ['email', 'password'] } } }, default_content_type='application/x-www-form-urlencoded' ) ) def login_view(request): # 视图逻辑...
配置完成后,Swagger界面中该POST接口会默认选中application/x-www-form-urlencoded作为内容类型。如果需要保留其他类型,只需在content字典中添加对应的键值对即可。
内容的提问来源于stack exchange,提问作者subba Raidu
相关产品推荐
相关产品推荐

