Building RESTful API With DRF(Django Rest Framework)

Ahmad Anondo
6 min readNov 18, 2018

--

So you have decided to build an awesome website, sort of like twitter or facebook. You are done building it & everything is running smoothly, life is fantastic, & the popularity of your website is spreading like wildfire. The problem is, the users are now demanding a mobile app for the website. Some of them are even asking for a desktop application. What do you do ? Set up your database connection from the scratch for the different platforms ?? NO!! Wouldn’t it be awesome if “someone” could present you with the data you require in a generic way, following a particular protocol & in a format which every device can understand without having to set up everything from the scratch? That “someone” could be the rest api.

What is REST API?

Rest stands for representational state transfer. Its a protocol for exchanging data among clients & servers regardless of the platform or language. Its entirely based on http and uses the http verbs for the communication. Thus rest is stateless i.e , each request & response are independent. Its the philosophy of rest to use the http methods:

GET: to retrieve data from server
POST:
to send data to the server
PUT: to update data
PATCH: also to update data but usually specific fields
DELETE: to…well duh, delete data
The communication is performed through a universal data structure like JSON or XML, with JSON being the dominant format for data interchange for the rest apis these days.

When dealing with REST there are certain terms that we will come across like Resources , Collections , Elements & Endpoints.

Endpoints

Endpoints are basically relative or absolute urls which normally results in a response. This responses are usually in JSON format. For example, http://takingrest.com/api/users here the /users is an endpoint. I have seen people building endpoints like /get_users , /delete_users and blah blah blah. Its not wrong but a standard restful api usually doesn't hint the request method on the endpoint rather they use /users as the only endpoint for the resource and the operation will be determined by the request method.

Resources

Usually every endpoint on a RESTful service is based on a resource. The model upon which the response is served is the resource. Users can be a resource , so can be bloggers in /users & /bloggers.

Collections & Elements

Depending on the request & endpoints, a response can be served on a number of resources or a particular resource. Working on more than one resource is a collection while a particular resource is called an element. Getting a collection usually includes endpoints like /users while elements are more specific like /users/1 where 1 is the id of a particular resource.

DRF

We all know about Django(hopefully) , the python web framework for the perfectionists with deadlines. Well, django rest framework was built on top of django with the sole purpose of building RESTful apis with pleasure. The more you get into it, the more addicted you become. It has been over a year with drf and i am yet to get bored(even the slightest).I am not gonna get into details about Django itself. Just going to focus on the DRF for now . So lets dive into some action.

Installing

Just hit this on the terminal:

pip install djangorestframework

Time to REST

First, open up the settings file of your project and add the rest framework among the installed apps along with the app we are gonna work on.

I have named my app api. I always find separate url files for the different apps helpful for simplicity and making the app reusable. So inside the url file for the api app set up the path like this:

Format suffixes are used because sometimes we want the endpoints to include the file extension like /messages.json or /messages.xml to specify the data format for communication. In this case i have only allowed the JSON format.
We will be making the view i have imported here in a minute. But first lets complete the routing by editing the main urls file in the settings:

We are all done with the routing for now. So lets create the view.

DRF provides with some awesome decorators. I have decorated my message view with the api_view which takes the allowed http methods as arguments. I have allowed just the get method for now. Had to add the format parameter as i am using the format_suffix_patterns(although not needed). And returning a json response.

Looks like we are ready to test our api. Lets do it by running the server like we do(with django) & check the response sent from my server. I use postman to test my apis.

Hitting the endpoint http://localhost:8000/api/messages gave me

{
“message”: “My first api”
}

So this is what a very very simple rest api consumption looks like. Now lets play around a bit. Lets make our view accept post requests as well.

Lets test this by sending some data

postman response

Worked like sugar. Now, onto some interesting stuffs. Before we advance, you should know what serializer is.

Serializer

Say you want to send some data received from an api to your friend in a portable storage device( don’t know what you would do that though). How do you save a python object on the hard drive? Or any other language data structures for that matter. Well, you can’t. So you serialize the data into a format worth distributing which every device can store & recognize. Serializing means to convert the native data type into a universal format, for our case JSON. Luckily drf provides us with awesome serializers to work with. Lets put it to use.

First lets create a model.

Next, lets create a serializers.py file in the api directory and create a serializer class.

Here i have specified each field & their types keeping the model structure in the mind. I have overrided the create method of the Serializer class which is extended by the class we have defined. This will be called whenever we get a post request & have to save some data.

Now lets update view.

One of the great things about django is that the codes define themselves. Then again, what i am doing here is passing all the books through the serializer class i have created specifying that there can be many of them(many = True) to serialize the data. And for the post method, doing more or less the same thing, but in this case getting the data from the request & also checking whether the data the serializer received is valid or not. If so, the serializer.save() is invoked which in turn calls the create method. Thats pretty much it. First, lets make a POST request, then receive the data with a GET request.

postman post request & response
postman get request & response

There you go. Btw don’t forget to make migrations.

Conclusion

To summarize , rest is an architecture which obeys the http protocol by separating the client & server concern & being stateless & using the http verbs to communicate about a resource. This communication is done via a universal data format(JSON/XML).
Django Rest Framework is a framework built on top of django with the sole purpose of building apis which fully obeys rest philosophy. What i have done have barely scratched the surface of what DRF can do. When you get into the details, you will realize how wonderfully it is built which almost forces you to follow the rest philosophy. Which is good because you will be knowing the best practices right from the start.

These tiny basics should get you started with rest and DRF. I have found the the drf documentation more than enough to get to know everything about building rest apis with django. There are many more awesome features of drf like , APIVIews , ViewSets/ModelViewSets , ModelSerializers & so on. Hopefully i will be able to write about them in the near future.

--

--

Ahmad Anondo

Programmer , lazy inventor, to be open source guy, foodie , football fan , not evil!