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:
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/")
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With