Photo by Annie Spratt on Unsplash

Django rest framework: How to make a simple file upload API using viewsets.

This article is to show you how easy it is to make a simple file upload API using Django viewsets. There are other alternatives to do the same but in this article, we will be using a viewsets, a serializer, and Django default routing to make an API to upload any file.

I am writing this post to mention what I had been faced with when dealing Django rest framework file upload initially, which will support those who are trying to find out how to do so.

Serializers.py

This is the part where we define the FileField and we will be using a Serializer to serialize the request which has the file from our API.

The serializer has one field which is thefile_uploaded . This field will have the uploaded file when you send a post request with the file.

Views.py

We will be using the ViewSet and Serializer to make the API for file upload.

The views only accept GET requests and POST requests only.

Urls.py

In this example, we are using a DefaultRouter which adds support for automatic URL routing to Django, and provides you with a simple, quick, and consistent way of wiring your view logic to a set of URLs.

This will make an API root when we go to https://localhost:8000.

API Root

The DefaultRouter thus provides these URL routes to do the create, retrieve, update, delete (CRUD) for our API.

You should have a list or a create function in your API viewset or else the API root will be blank.

Working

When you got to localhost:8000 you will see the API Root and on clicking the URL you will be redirected to the API page. So what I have done in my views is when a get request is sent it will give you a response saying GET API.

GET API response

But when you send a POST request with a file you will get the response as POST API and you have uploaded a <CONTENT TYPE> file The CONTENT TYPE is the type of file you have uploaded for example if you upload the HTML file you will get a response like follows.

POST API response
The upload part

The important thing to note down is that the upload portion of the API page will be blank if you don’t have the create or put function in the view set.

Works at @impressAI

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store