axnsan12 / drf-yasg

Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.
https://drf-yasg.readthedocs.io/en/stable/
Other
3.42k stars 439 forks source link

cannot add form parameters when the request has a request body #767

Open rohitkishnan opened 2 years ago

rohitkishnan commented 2 years ago

Not able to generate a swagger file with multipart/form-data content-type in request

Description

I have a POST request to upload a document where I send the document sent in multipart/form-data. I have tried to describe the form data as such ![image](https://user-images.githubusercontent.com/54931201/150966253-be4f6f71-7dd5-4fb0-90b6-a21796aa9692.png) This is how my request looks in postman ![image](https://user-images.githubusercontent.com/54931201/150966369-be70b412-7a33-4772-a5f8-db4a9448a363.png) When I try to generate a swagger file. It gives me the following error drf_yasg.errors.SwaggerGenerationError: cannot add form parameters when the request has a request body; did you forget to set an appropriate parser class on the view? ## Minimal Reproduction ```code @swagger_auto_schema( operation_id='Create a document', operation_description='Create a document by providing file and s3_key', manual_parameters=[ openapi.Parameter('file', openapi.IN_FORM, type=openapi.TYPE_FILE, description='Document to be uploaded'), openapi.Parameter('s3_key', openapi.IN_FORM, type=openapi.TYPE_STRING, description='S3 Key of the Document ' '(folders along with name)') ], responses={ status.HTTP_200_OK: openapi.Response( 'Success', schema=openapi.Schema(type=openapi.TYPE_OBJECT, properties={ 'doc_id': openapi.Schema(type=openapi.TYPE_STRING, description='Document ID'), 'mime_type': openapi.Schema(type=openapi.TYPE_STRING, description='Mime Type of the Document'), 'version_id': openapi.Schema(type=openapi.TYPE_STRING, description='S3 version ID of the document') }) ) } ) ```
rohitkishnan commented 2 years ago

@axnsan12 Could you please help me with this

PaulWay commented 2 years ago

You're probably better off using a DRF serializer here to be honest. You then use the request_body=FileUploadSerializer parameter to swagger_auto_schema to set the manual parameters. I'm assuming from your example here that this is in a POST request.

TridipCDas commented 2 years ago

@rohitkishnan Add parser_classes = (parsers.MultiPartParser,) to the class. It should work.

Lvc4 commented 1 year ago

@TridipCDas from where can i import parsers.MultiPartParser?

moonlightCoder2002 commented 1 year ago

@Lvc4 you can do from rest_framework.parsers import MultiPartParser

abhisheksinghsrijcon commented 1 year ago

In My case it was parser_classes = (MultiPartParser, FormParser, JSONParser)

After removal of JSONParser things were Good