[英]How do I include 400 validation errors in drf-spectacular?
I want to view validation details in 400 response as they can be reutrned by the serializer.我想查看 400 响应中的验证详细信息,因为它们可以由序列化程序返回。 The serializer can return errors depending on a missing field or invalid value and I want the documentation to indicate which kind of errors can appear with the status code 400. Something like this序列化程序可以根据缺失的字段或无效值返回错误,我希望文档指出状态代码 400 可能出现哪种错误。像这样
200: Success 200:成功
400: [ { "organisation_id": [ "This field is required." 400: [ { "organisation_id": [ "此字段是必需的。" ] } ] #include any validation errors that can come from the serializer ] } ] #include 任何可能来自序列化程序的验证错误
My code currently is this我的代码目前是这个
@extend_schema(
summary="Create a new transaction",
responses={
201: OpenApiResponse(
description='Success',
),
400: OpenApiResponse(
description='Bad request. One or more errors occured.',
),
},
)
And currently this outputs 200: Success目前这输出 200: 成功
400: Bad request. 400:错误的请求。 One or more errors occurred.发生了一个或多个错误。
Is there something like有没有像
400: OpenApiResponse(description=customSerializerErrors,
), #customSerializerErrors is something i hope gets errors from the serializer
drf-spectacular
works on the basis of serializers. drf-spectacular
在序列化程序的基础上工作。
OpenApiResponse
is a convenience wrapper that is not needed most of the time. OpenApiResponse
是一个方便的包装器,大多数时候不需要。 In fact here, it is probably not doing what you expect.事实上,在这里,它可能没有按照您的预期进行。 You would need to give OpenApiResponse(response=SomeSerializer)
, otherwise you are saying there is no response body, because the default is None
== no response.您需要提供OpenApiResponse(response=SomeSerializer)
,否则您是说没有响应正文,因为默认值为None
== no response。
You likely want to do this:您可能想要这样做:
@extend_schema(
summary="Create a new transaction",
responses={
201: YourSerializer,
400: YourErrorSerializer,
},
)
There is no predefined YourErrorSerializer
because Django's error_handler
is highly dynamic and cannot be inspected.没有预定义的YourErrorSerializer
因为 Django 的error_handler
是高度动态的,无法检查。 At the moment you would need to write this YourErrorSerializer
yourself.目前,您需要自己编写这个YourErrorSerializer
。 Note that this serializer is not actually used, but is merely telling spectacular how the response is structured.请注意,此序列化程序并未实际使用,而只是说明了响应的结构方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.