5

I am not able to find any support for making a schema for the file upload API. The Swagger UI must have a button allowing a tester to upload a file for testing purposes. I am using firebase as a database so serializers and models don't come into the picture. I am using only Django's rest framework.

I have looked at drf-yasg's documentation that suggests using Operation for file upload. But It is a very abstract and obscure documentation.

Tough Guy
  • 53
  • 1
  • 4

3 Answers3

14

Make sure you specify the parser_classes in your view. By Default it's JSON parser which doesn't handle file uploads. Use either MultiPartParser or FileUploadParser

class MyUploadView(CreateAPIView):
    parser_classes = (MultiPartParser,)
    ...

    @swagger_auto_schema(operation_description='Upload file...',)
    @action(detail=False, methods=['post'])
    def post(self, request, **kwargs):
        # Code to handle file

Blux
  • 196
  • 1
  • 6
  • Yes, but how do we create a schema for this in drf_yasg? – Tough Guy Aug 07 '19 at 06:44
  • 1
    @ToughGuy, you should be able to add schema via providing your serializer via view's class attribute (`serializer_class`) or via `@swagger_auto_schema` decorator; This answer has helped me. Should be marked as accepted imo. – IgorNikolaev Apr 01 '20 at 14:29
2

Here is working example from my project

from rest_framework import parsers, renderers, serializers, status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response


class ContactSerializer(serializers.Serializer):
    resume = serializers.FileField()


class ContactView(GenericAPIView):
    throttle_classes = ()
    permission_classes = ()
    parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.FileUploadParser)
    renderer_classes = (renderers.JSONRenderer,)
    serializer_class = ContactSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid(raise_exception=True):
            data = serializer.validated_data
            resume = data["resume"]
            # resume.name - file name
            # resume.read() - file contens
            return Response({"success": "True"})
        return Response({'success': "False"}, status=status.HTTP_400_BAD_REQUEST)
Ryabchenko Alexander
  • 10,057
  • 7
  • 56
  • 88
1

Check out this issue. You can find how to use @swagger_auto_schema to create something like this

enter image description here

Silvio Messi
  • 123
  • 1
  • 2
  • 9
  • I used the same but my request.FILES is not showing anything when i upload via swagger. If i use postman, its working fine. – sap Mar 24 '23 at 14:07