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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:35:19