Django rest APIs, automate documentation?

3.4k views Asked by At

I tried documenting the APIs while writing viewsets and using django rest docs. I am having the following problems:

  • if I try to send values for reverse related field, it takes list of values, but when sending the data in Form-data, it comes as a string.

  • There is no option for file upload in the docs UI.

Following is my code:

models.py

class Area(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=100)
    address = models.TextField()
    image = models.ImageField(upload_to='area/')
    created_on = models.DateTimeField(auto_now_add=True)
    modified_on = models.DateTimeField(auto_now=True)
    zipcode = models.CharField(max_length=15, null=True)
    is_verified = models.BooleanField(default=False)

    class Meta:
        ordering = ('-modified_on',)



class Email(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    email = models.EmailField()
    area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, related_name='email')


class Phone(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    phone = models.CharField(max_length=15)
    area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, related_name='phone')

view.py

class AreaViewSet(viewsets.ModelViewSet):
    """
    create:
    Create a new area instance.

    """
    serializer_class = AreaSerializer
    parser_classes = (FormParser, MultiPartParser,FileUploadParser)
    queryset = User.objects.all()
    permission_classes = [AllowAny, ]
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('first_name',)

    def create(self, request):
        data = self.request.data
        with transaction.atomic():
            name = data['name']
            address = data['address']
            email = json.loads(data['email'])
            phone = json.loads(data['phone'])
            zipcode = data['zipcode']

            area = Area.objects.create(name=name,address=address, zipcode=zipcode)

            for i in email:
                Email.objects.create(email=i['email'], area = area)

            for i in phone:
                Phone.objects.create(phone=i['phone'], area=area)

            return Response({'status': {'code': status.HTTP_200_OK,
                                        'error': None,
                                        'message':' Area has been added.'
                                        },
                             'data': None})

serializer.py

class AreaSerializer(serializers.ModelSerializer):
    email = EmailSerializer(many=True)
    phone = PhoneSerializer(many=True)

    class Meta:
        model = Area
        fields = '__all__'

i am using http://www.django-rest-framework.org/topics/documenting-your-api/

There is no file upload in image field in default docs.

enter image description here

Thanks

2

There are 2 answers

1
Jonas Amara On

Ok first , to be more pratical, your create function needs to be like this

def create(self,request, *args,**kwargs):
       data = request.data
       logger.debug("%s" % data)
       request = (self.__dict__['request'])
       #parse the rest of your code here 

Also , why can't you swagger to easily set up your documentation it's going to be more easier for you, or maybe it's a requirement for you

1
Kostas Livieratos On

Another good idea would be to use Swagger. In Django, especially using DRF, you have the opportunity to integrate with Django Rest Swagger and generate automatic documentation for your endpoints. The only requirement is to provide with docstrings-documentation your API classes and methods.

ps: I have no affiliation with django rest swagger package or authors, just a frequent user