django rest 框架 - 如何将 post 参数添加到 api 文档(drf_yasg)? [英] django rest framework - How to add post parameters to api document(drf_yasg)?
问题描述
x_param = openapi.Parameter('x', in_=openapi.IN_FORM, description='srring',
type=openapi.TYPE_STRING)
y_param = openapi.Parameter('y', in_=openapi.IN_FORM, description='string',
type=openapi.TYPE_STRING)
@swagger_auto_schema(method='post', manual_parameters=[x_param,y_param])
@api_view(['POST'])
def test(request):
pass
我使用 drf_yasg
作为招摇.
我做了上面的编码并用swagger测试了它,当我用Chrome检查时,请求有效负载是x = 124 &y = 124124
.
I did the coding above and tested it with swagger, and when I checked with Chrome, the request payload is x = 124 & y = 124124
.
并且,出现以下消息,发生了错误的请求错误.
And, with the following message, a bad request error occurred.
{
"detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)"
}
swagger中加post参数有错吗?
Is it wrong to add post parameters to the swagger?
推荐答案
问题是你在swagger中添加form
类型的参数,但是你的视图似乎期望请求中有一个json有效载荷身体.在这种情况下,您可能希望将 request_body
与 openapi.Schema
对象一起使用.
The problem is that you are adding parameters of type form
to swagger, but your view seems to expect a json payload in the request body. In that case you probably want to use request_body
with an openapi.Schema
object.
@swagger_auto_schema(method='post', request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'x': openapi.Schema(type=openapi.TYPE_STRING, description='string'),
'y': openapi.Schema(type=openapi.TYPE_STRING, description='string'),
}
))
@api_view(['POST'])
def test(request):
pass
这会自动将您的 Schema
包装到 in_=openapi.IN_BODY
的 Parameter
中.请参阅 https://drf-yasg.readthedocs.io/en/stable/openapi.html 了解详情.
This will automatically wrap your Schema
into a Parameter
of in_=openapi.IN_BODY
.
See https://drf-yasg.readthedocs.io/en/stable/openapi.html for details.
当然,首选的方法是使用基于类的 GenericAPIView
和 Serializer
,这将简化视图代码和文档内省.
Of course, the preferred way would be to use a class-based GenericAPIView
together with a Serializer
, which would simplify both the view code and the doc introspection.
这篇关于django rest 框架 - 如何将 post 参数添加到 api 文档(drf_yasg)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!