Skip to content

Instantly share code, notes, and snippets.

@prodeveloper
Last active September 13, 2017 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prodeveloper/5d770ffda934f8e9444aaa634e494870 to your computer and use it in GitHub Desktop.
Save prodeveloper/5d770ffda934f8e9444aaa634e494870 to your computer and use it in GitHub Desktop.
An introduction to Django Rest Framework

Introduction

In our class today, we shall be exploring a new and very powerful library called Django rest framework

The library allows you to get a working API of your models with very little coding.

This API will be essential for your frontend and mobile classes once you start building full scale applications.

Let’s see how we can incorporate it into our model

Step 1

We start by installing the needed packages into our application.

If you have not opened your application in a while, you may have lost write access. This is an issue with c9 configuration.

So ensure you can write to the folder by typing the following command to your bash terminal

You can now install the packages needed

First the framework

Then markdown support

Then filter support

We will be using this libraries as we proceed.

As usual, to ensure you can actually use the newly installed library, register it in INSTALLED_APPS on your settings.py file.

Step 2

With the library setup, we now need to build the views.

We went all requests that go to /api/ to be routed to the view.

The first thing to create is a serializers.py module. This module will contain instructions to Django on how to display our information. This is analogous to what we did when we registered our models in admin.py

Inside the file, type in the serializer for the student module as follows

You notice that we have both imported our model as well as the serializer. You will always need to import modules before using them.

Step 3

Now that we have a way to represent our data, let us wire it up to our view.

Django rest framework provides a way of doing this via its viewset.

Note we now imported the viewset module from rest_framework as the serializer we just created.

Step 4

Finally we are now ready to wire it all up to the urls.py module so that it can be accessed externally.

Type the code below into your urls module.

Be very careful to ensure everything has been imported.

Run the application and navigate to /api endpoint. You should see

You can now navigate to the created view for the students model api

Note the form just below that allows you to add new data to the set.

Assignment

Create an endpoint for your Course model such that when I hit api/courses/ I see a list of courses and a form to add more courses.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment