django rest framework - How to add post parameters to api document(drf_yasg)?
Asked Answered
P

1

28
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

I used drf_yasg as a swagger.

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)"
}

Is it wrong to add post parameters to the swagger?

Polycotyledon answered 19/6, 2018 at 12:59 Comment(4)
The in_=openapi.IN_FORM tells it that you expect it to be a form, while your API is configured to accept JSON?Overlay
@SungHoKim based on the JSON response, the server seems to be looking for valid JSON data in the POST body. Did you try formatting your request body accordingly? Maybe like {'x': 124, 'y': 124124} ?Moustache
Try changing your openapi.IN_FORM to openapi.IN_BODYAlvaroalveolar
So I just want tot point out that I switched from drf-yasg to drf-specacular and haven't looked back. It was way simpler at customizing and is actively maintained.The last commit on drf-yasg was 3 months ago... drf-spectacular.readthedocs.io/en/latest/customization.htmlCardamom
I
35

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

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.

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.

Inefficiency answered 22/12, 2018 at 18:15 Comment(3)
Of course, the preferred way would be to use a class-based GenericAPIView together with a Serializer : Is there a way to specify write / read serializer separately?Bede
Same issue in classbased views, https://mcmap.net/q/504334/-drf-yasg-custom-json-bodyAutoradiograph
This answer saved my time and fixed my issueSyphon

© 2022 - 2024 — McMap. All rights reserved.