Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to upload files using the browsable API in Django REST framework?

I need to test an API that uploads a file. How do I do this from the browsable API. The browsable API page looks like this:

enter image description here

Is there any way to upload files using this interface?

views.py:

class TrainingData(APIView):
"""
API for getting the training data
"""


def post(self, request,  format=None):
    """
    Receives the data in the form of a POST request
    """
    print request.data
    serialized = TrainingSerializer(data=request.data)
    if serialized.is_valid():
        file_obj = request.data['file']
        print "its working"
        return Response(status=204)

    return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py:

class TrainingSerializer(serializers.Serializer):
"""
Serializer for the training data input
"""

uploaded_file = serializers.FileField(use_url=settings.BASE_DIR+"/api/uploaded_files/")
like image 460
Vinay Avatar asked Aug 31 '15 12:08

Vinay


People also ask

How do I handle file upload in Django REST framework?

You just need to put the field in your ModelSerializer and set content-type=multipart/form-data; in your client. BUT as you know you can not send files in json format. (when content-type is set to application/json in your client). Unless you use Base64 format.

What is browsable API in Django REST framework?

The browsable API feature in the Django REST framework generates HTML output for different resources. It facilitates interaction with RESTful web service through any web browser. To enable this feature, we should specify text/html for the Content-Type key in the request header.

Is Django GOOD FOR REST API?

If you are only interested in building a REST API backend, Django is an overkill. However, you can use the Django REST framework, which is a community-funded project by Encode. It uses Django as the underlying engine by providing a more straightforward interface that is specific to REST API development.


1 Answers

The Django REST framework automatically generates an appropriate form in the browsable API only when using Generic Based views. Switching to Generic Based views solved my problem.

Using the following change I was able to get a file upload field

from rest_framework import generics  

class TrainingData(generics.CreateAPIView):
    "API for getting the training data"

    serializer_class = TrainingSerializer
like image 76
Vinay Avatar answered Sep 22 '22 06:09

Vinay