Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest swagger document shows choose file as string

I am creating simple swagger documentation with django rest framework, django rest swagger.

Python: 3.6
Django: 3.0.3
django-rest-swagger: 2.2.0
djangorestframework: 3.11.0

Here is Models.py

class Image(models.Model):
    file = models.ImageField(upload_to='photos', null=True, blank=True)
    is_active = models.BooleanField(default=False, null=True, blank=True)
    created_at = models.DateTimeField(default=timezone.now)

    class Meta:
        db_table = 'image'

    def __str__(self):
        return self.file.name

and I created serializers.py

class ImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Image
        fields = ('id', 'file', 'created_at')

Also here is image_view.py

from rest_framework import generics
from rest_framework.parsers import FormParser, MultiPartParser, FileUploadParser

from api.serializers import ImageSerializer
from api.models import Image


class ImageView(generics.CreateAPIView):
    serializer_class = ImageSerializer
    parser_classes = (FileUploadParser, )

    def post(self, request, *args, **kwargs):
        """
           Image Moodel
           ---
           parameters:
               - name: file
                 type: file
           responseMessages:
               - code: 201
                 message: Created
       """
        file = request.data.get('file')
        image = Image(file=file, name=file.name)
        return self.create(request, *args, **kwargs)

Image upload shows as string.

enter image description here

How can solve this issue?

like image 549
Softdev Avatar asked Nov 06 '22 10:11

Softdev


1 Answers

Quickly consulting the Swagger documentation, it looks like depending on which OpenAPI version you're targeting this is the correct behavior. Version 3 of the OpenAPI specifications does not support concept of a file type whereas v2 does have a concept of a file format. This makes sense considering the RFC that defines JSON, RFC7159, has a limited list of value types that are considered as part of valid JSON.

More information can be found here

Addendum: I can't speak directly for the framework you're using to generate the documentation but for image/file upload, the format attribute can be used to specify how the file is suppose to be uploaded, i.e. binary, base64 encoded. You can find more information here regarding File Upload and the OpenAPI specification

Looking into your framework documentation, it also appears that it targets the older Swagger 1.2/OpenAPI v2 spec in which case this is still the correct behavior as detailed in the OpenAPI v2 on data types

like image 54
xinkecf35 Avatar answered Dec 01 '22 19:12

xinkecf35