Creating a production ready API with Python and Django Rest Framework – part 2

In the first part of this tutorial we have seen how to create a basic API using Django Rest Framework. This second part will explain how to implement POST methods and add different levels of permissions and authentication. If you are starting from part 2, you may want to checkout the source code at this exact point:

A step back

Before showing how easy it is to implement a POST method for our existing API, I want to do a step back and show you the “manual way”, using just the APIView class. Edit the file catalog/ and change the code in this way:

If we try to use the API again (from the browser of from the http client), it will still work in the same way. The difference here is that we are using the very basic APIView class and we have explicitly defined the GET method for it.

Implementing a POST method with APIView

An API is not being used at its full potential if it’s read only. We are going to implement a POST method for the existing view and testing it with httpie client again. First of all we need to add an import to catalog/

then we add this method to our ProductList class:

Now let’s test our POST method we just implemented:

It works! In case something doesn’t work, try to fetch the source code at this point:

Implementing a POST method with ListCreateAPIView

Do you remember when I mentioned at the beginning that there is an easy way to do the same thing? I wasn’t cheating. Let’s change again our old code in catalog/ but this time we will use a different base class:

let’s test this again with httpie:

We just POSTed some data on the API! How can it work? Well, we have changed the base class from ListAPIView to ListCreateAPIView. This particular class implements a generic POST method that will accept and validate all the fields through the specified serializer.


Now our API let us add products to the catalog, amazing! But… is it exactly what we want? In a real scenario we don’t want any random user to be able to add products in our database, so we are going to protect the POST method allowing only Admin users.

Before digging into Django Rest Framework permissions, we need to setup an authentication system. For simplicity we will implement TokenAuthentication. As first step we need to edit and insert rest_framework.authtoken in the INSTALLED_APPS:

after this, we need to add TokenAuthentication as default authentication class (append this in at the end):

Finally we need to add a particular URL to the project so that clients will be able to call an endpoint passing username and password to get a token back. Edit drftutorial/ and make it’s like this:

Don’t forget to re-run the migrations, because TokenAuthorization needs to change a couple of tables:

In case you had any problem changing the code up to this point, you can always fetch the related git tag:

Testing the Authentication

Before testing the authentication, make sure you created at least the Django superuser with:

now let’s try to obtain the token we will need later for our API calls:

We will need to pass this token in every API call we want to be authenticated. The token is being passed through the “Authentication” header parameter.

API Permissions

Authentication is something that identify the user with a particular system. Permissions instead are the level of things that are allowed or not allowed for a particular user. In our case we said we want to let Admin users to be able to POST new products and we want to let even anonymous users to GET the product list.

Django Rest Framework has some built-in classes that we can apply to our views to define the level of permissions. We could have used the IsAdminUser class, but it would not allow anonymous users to perform the GET request. Or we could have used IsAuthenticatedOrReadOnly class, but this would allow any registered user to add products (and we want to let only admins).

Or…we can define our own permission class and have exactly what we want. Create a new file catalog/

Just as a side note, SAFE_METHODS are GET, HEAD and OPTIONS. These method are considered “safe” because they don’t change any existing data. Open catalog/ again, import this at the beginning:

and set this as permission_classes to ProductList:

Let’s now try to add a new product using the token we got before (you will have to use your own token of course, mine only works on my local db):

It worked! We have now protected our API so that not admin people can’t create any product. If you have any problem with the code, you can check it out with this tag:

Wrapping Up

We have now implemented the POST method to add new products to our catalog. In the next episode we will see how to implement endpoints to get a single product, to update or delete products and finally we will allow registered users to send a review for a specific product.

Feedback Please

I know, this blog doesn’t have any “comment” feature (I was tired of dealing with spam), but if you want to provide some feedback you can still do it by email. Just visit my About page, you will find my email there.

Creating a production ready API with Python and Django Rest Framework – part 1

The aim if this tutorial is to show how to create a production ready solution for a REST API, using Python and Django Rest Framework. I will show you how to first create a very basic API, how to handle the authentication and permissions and I will cover deployment and hosting of images. The full source code of the tutorial is available at:

Summary of the complete tutorial

  1. Create the basic structure for the API
  2. Add Authentication and POST methods
  3. Handling details and changes to existing data
  4. Testing the API
  5. Switching from Sqlite to PostgreSQL
  6. Hosting the API on Heroku
  7. Add an Image field and save images to S3

Create the basic structure for the API

For this tutorial I will assume you have correctly installed at least Python (I will use Python 2.7.x), virtualenv and virtualenvwrapper on your system and I will explain how to create everything else step by step.

Note: at the time of writing, the tutorial has been based on Django 1.10.1 and Django Rest Framework 3.4.7

Creating the main project structure

Data Model

We will create the API for a generic products catalog, using a very simple structure (to keep things simple). Edit the file catalog/ adding these lines:

after creating the model, we need to add ‘catalog’ application to INSTALLED_APPS. Edit and add the app at the end of the list:

at this point the Django application will be recognised by the project and we can create and apply the schema migration:

API Serializer

Serializers are those components used to convert the received data from JSON format to the relative Django model and viceversa. Create the new file catalog/ and place this code inside:

In this case we are using a ModelSerializer. We need to create a new class from it, and specify the model attribute, that’s it. In this case we also specify the fields we want to return.

API View

The serializer alone is not able to respond to an API request, that’s why we need to implement a view. In this first version of the view (that we will improve soon) we will “manually” transform the data available in the serializer dictionary to a JSON response. In catalog/ add this code:

At this point we need to tell our Django app to use this API view when a certain URL is requested. We first need to add this code in catalog/

and finally we need to add this to drftutorial/

Testing our work

At this point we should be able to start our Django app:

Let’s install a tool that will help us to test the API:

now we can use it to call our URL:

It works! It’s an empty response of course, because we still don’t have any data to show, but we will see later how to load some example data in our database. If you have been able to follow the tutorial up to this point, that’s good. If not, don’t worry. You can checkout the code at exactly this point of the tutorial doing:

Improving the API View

There is a quicker and more efficient way of implementing the same API view we have seen before. We can use a class based view, in particular the APIView class and also have the JSON response implemented automatically. Change the code inside catalog/ with this one:

You will also have to change catalog/ in this way:

You can check the source code for this step of the tutorial with:

There is also another way of writing the same view. Let’s try it with ListAPIView. Edit catalog/ again and substitute the code with this one:

With a ListAPIView we are basically creating a read-only API that is supposed to return a list of items. We need to specify a queryset and the serializer_class parameters. Once again, you can get up to this point, checking out the related git tag:

Creating Initial Data

An API that doesn’t return any data is not very useful, right? Also, at the moment we haven’t implemented yet any feature that let us insert any data. That’s why I’ve created a data migration for you that will insert some data for you. You may notice that the example data contains some Italian products… out of the scope of this tutorial, I strongly advise you to google this products and if you ever happen to visit Italy, try them. You won’t regret!

Going back to our data migration, you first have to create an empty one with:

and then open the file that has been created under catalog/migrations/ named 0002_….. (your name will be different from mine, so just edit the one starting with 0002 and you will be fine) and fill it with this code:

to apply the migration we just created, just do:

If you try to test the API again from the command line, you will get these products back:

Again, you can get up to this point with:

One more thing…

No, we are not going to present a new amazing device, I’m sorry, but I want to show you a nice Django Rest Framework feature you can have without much additional work. Edit and add rest_framework to the list of INSTALLED_APPS:

Now, if you are still running the Django app, try to visit this url from your browser:
That’s very nice, isn’t it? You can have browsable APIs at no cost.

Wrapping Up

I’ve mentioned at the beginning that this is just the first part of my API tutorial. In the next part I will show you how to let the consumer of your API add some products and leave reviews (we will introduce a new model for this). Also, we will see how to set proper permissions to these new API methods so that only admin users will be able to add products while normal users will be able to add reviews. So, if you feel ready, you can begin to follow the second part of this tutorial:


Some parts of this tutorial and a few examples have been taken directly from the original Django Rest Framework tutorial.

Using Python ipdb from Jupyter

If we try to use the usual ipdb commands from a Jupyter (IPython notebook)

we will get a similar error:

The solution is to use Tracer instead:


Using a light sensor with BBC micro:bit and MicroPython

A light sensor is a small component with a particular characteristic: it is basically a resistor and its resistance decreases if the light is more intense. To use it with micro:bit we need to use one of the analogic ports. To build this circuit you will need a breadboard, 3 jumper wires, a 10k resistance and possibly a Kitronik breadboard kit.

The project

I wanted to realise a simple project where, depending on the light intensity captured by the light sensor, the micro:bit shows an image of the Sun if the light is intense and an image of the Moon if the light is less intense.

Here is the complete circuit scheme:


“Image Copyright © Kitronik”


and here is a picture of the finished project I created:


The source code I needed is available here:

and as a demo I realised this small video:

Prototyping BBC micro:bit projects with Kitronik breadboard kit

BBC micro:bit has a few IO pins that can be used to interact with external devices. The problem with the board is that it’s not easy to connect the classic jumper wires (those that we normally connect to a breadboard) to the micro:bit, unless using a crocodile clip and being limited to just 3 pins.

Kitronik breadboard kit solves this problem, offering an interface where the micro:bit can be plugged and all the pins are easily connectable to the breadboard using normal male/female jumper wires.

I’ve built a very simple circuit following an example you can find on this manual


To build the circuit you also need 4 male/female jumper wires and two buttons. All this circuit does is to connect the buttons to the micro:bit pins that relate to those buttons. Basically pressing those buttons is the same as pressing button A or button B on the micro:bit board. Here you can see the schema in detail:

Screenshot 2016-02-07 14.30.36

“Image Copyright © Kitronik”

I’ve also made a short video so that you can see it in action:

And of course the source code is available too: