How to Develop Restful A.P.I.s in Django

Introduction

The project looks into how you can build Restful A.P.I.s in Django. It can be a good start for a business that sells data or offer technology services that can be intergrate to mobile devices or other platforms. Through this, it will allow other developers to register and log in for them to have access to their APIs.

Intended audience: Who the article is for

This article targets python/Django developers who would want to build restful API for their systems to allow other users to integrate with or any organization looking on how to start development and management of access to their APIs, which they can later monetize e.g. rate per API call

Case Study: What the article is going to cover

The project will create three core APIs that other users will interact with in order to fetch data and other support APIs, a user will have to sign up or log in to our platforms in order to get an authorization key. Using this key they will then be able to make calls to our APIs, the API system also forces the users to first subscribe to the APIs they want to use for them to have access to it, but also giving them the option of unsubscribing.

The subscription of users will allow the firm hosting the APIs to know which APIs people interact with the most as well as regulate their access.

The application is built using python programming language in Django Framework.

How it will work

The system is a repository of cities around the world, a user first calls the continents API to get a list of continents, they then use the content id to call the countries API to get the countries linked to the specific continent, they then use the country’s id to call the cities’ API to get the cities linked to that specific country. These three APIs are the core APIs, below are the other APIs to be developed.

  • Subscription API – an API responsible for subscribing a user to a particular API
  • Get Subscriptions API – an API responsible for returning the APIs a user has subscribed to
  • Unsubscribe API – an API responsible for unsubscribing a user from an API
  • Get API – an API responsible for returning all APIS the system supports

Requirements:

  1. Some knowledge of Python and Django
  2. Some knowledge on using Postman

Getting started with the Web App

Creating a Django Project

  1. From your terminal navigate to the folder/location your project is to reside
  2. We will create a Django project called “djangorestapis”, type the command: django-admin startproject djangorestapis
  3. From the terminal navigate into the created project folder, where you will create and activate your project’s virtual environment by typing in the terminal the command “python –m venv venv”
  4. In windows, type “venv\Scripts\activate” in the terminal
  5. In Mac/Linux, type ”source venv/bin/activate” in the terminal
  6. After your virtual environment has been activated, run the code below in the terminal to install the following python packages
    • “pip install django” : python package to be used in building the web app
    • “pip install djangorestframework”: python package used in creating REST A.P.I.s
  7. Create your first Django app by typing in the terminal the command: “python manage.py startapp users”
  8. Create your second Django app by typing in the terminal the command: “python manage.py startapp countries”
  9. Create a SQLite database that will used by the project by typing in the terminal the command: “python manage.py makemigrations”
  10. Apply database changes by typing in the terminal the command: “python manage.py migrate”
  11. Start your server by typing on the terminal the command: “python manage.py runserver”
  12. If the server starts successfully there should be a login webpage up and running on the location: http://127.0.0.1:8000/admin
  13. While in the terminal type Ctrl+C to stop the server
  14. Everything from now on will be performed inside this python activated environment

We are stopping the server so that we can create the database tables first and then apply the changes before restarting the server

Configure Django Project Settings

  1. Open your Django project folder: “djangorestapis”
  2. Locate a folder with a similar name to your Django project folder, this folder is in the same directory as your “users” app folder
  3. Inside this folder is a python file labeled “settings.py”
  4. Open the “settings.py” file and locate the python variable ALLOWED_HOSTS, which is a python list located close to the start of the file
  5. Inside the ALLOWED_HOSTS enter the “localhost” URL created as well as the “127.0.0.1” URL, this is a security measure by Django to ensure that the web app can only be accessed via the set URLs. Below is an example of how to do so:
  1. Inside the “settings.py” file, locate the variable INSTALLED_APPS
  2. The variable installed_apps is a list where you will register the apps we just created
  3. Insert the code below inside the list:
  4. We also need to register the Django rest framework packages that we will use to create restful APIs as well as authentication methods, inside the INSTALLED_APPS python list paste the code below:
  5. Paste code below after the INSTALLED_APPS python list variable in the settings.py file,  the first section of code is to enable token authentication on the APIs and the last section provides a class that is used to check if a user has authenticated before accessing data.

Creating Countries Database Tables

  1. Open your Django project folder in your code editor
  2. Open the “countries” app folder
  3. Open or create the “models.py” file
  4. We now create the database tables related to the “countries” app we created, which are:

Modules to be imported

The modules to be imported that will be used to build the database table are:

from django.db import models –  This will be used to convert a python class to a database table

from django.contrib.auth.models import User –  The default Django user database table

To import the above methods, navigate into the “countries” folder and open a file labeled “models.py” and paste the code below:

Continent Table Logic

This table will hold the name of the continents created. It will include the continent’s name. It will have the following fields:

name –This column will hold the name of the continent with a maximum character length of 50

__str__ –This is a method in the class “Continent” class we will create that will be responsible for returning back the string representation of objects or table records created in the Post table. The string representation method will return is the name of the continent

__repr__–This is a method in the class “Continent” class we will create that will be responsible for returning back the object representation of the database object created in the Post table. The syntax of the object representation to be returned is “Continent (name=’Africa’)”  

To create the above “Continent” tables in your project folder, navigate into the “countries” folder and open a file labeled “models.py” and paste the code below:

Country Table Logic

This table will hold the name of the countries related to each continent created. It will include the country’s name, code and a foreign key to the related continent. It will have the following fields:

name –This column will hold the name of the country with a maximum character length of 50

code –This column will hold the code of the country with a maximum character length of 5

continent –This column will hold the foreign key to the related country

__str__ –This is a method in the class “Country” class we will create that will be responsible for returning back the string representation of objects or table records created in the Post table. The string representation method will return is the name of the country

__repr__–This is a method in the class “Country” class we will create that will be responsible for returning back the object representation of the database object created in the Post table. The syntax of the object representation to be returned is “Country (name=’Kenya’,code=’KEN’)” 

To create the above “Country” tables in your project folder, navigate into the “countries” folder and open a file labeled “models.py” and paste the code below:

Cities Table Logic

This table will hold the name of the cities related to each country created. It will include the city’s name and a foreign key to the related country. It will have the following fields:

name –This column will hold the name of the country with a maximum character length of 50

country –This column will hold the foreign key to the related country

__str__ –This is a method in the class “Cities” class we will create that will be responsible for returning back the string representation of objects or table records created in the Post table. The string representation method will return is the name of the city

__repr__–This is a method in the class “Cities” class we will create that will be responsible for returning back the object representation of the database object created in the Post table. The syntax of the object representation to be returned is “Cities (name=’Nairobi’, country=CountryObject)” 

To create the above “Cities” tables in your project folder, navigate into the “countries” folder and open a file labeled “models.py” and paste the code below:

API Table Logic

This table will hold the name of the API and API code names. It will include the API’s name and code. It will have the following fields:

name –This column will hold the name of the country with a maximum character length of 50

code –This column will hold the code of the country with a maximum character length of 5

__str__ –This is a method in the class “API” class we will create that will be responsible for returning back the string representation of objects or table records created in the Post table. The string representation method will return is the name of the API appended with the word ’API’

__repr__–This is a method in the class “API” class we will create that will be responsible for returning back the object representation of the database object created in the Post table. The syntax of the object representation to be returned is “API (name=’Continent’,code=’CON’)” 

To create the above “API” tables in your project folder, navigate into the “countries” folder and open a file labeled “models.py” and paste the code below:

Subscription Table Logic

This table will hold the list of users and the APIs they have subscribed to. It will include a foreign key to the related user and a foreign key to the API. It will have the following fields:

user –The foreign key to the related user

api –The foreign key to the related API

__str__ –This is a method in the class “Subscription” class we will create that will be responsible for returning back the string representation of objects or table records created in the Post table. The string representation method will return is the name of the city

__repr__–This is a method in the class “Subscription” class we will create that will be responsible for returning back the object representation of the database object created in the Post table. The syntax of the object representation to be returned is “Subscription (user= UserObject, api=APIObject)” 

To create the above “Subscription” tables in your project folder, navigate into the “countries” folder and open a file labeled “models.py” and paste the code below:

Register Countries Database Tables

This allows the database tables created to be accessible via the Django admin interface. To do so:

To do this:

  1. Open the “countries” app folder
  2. Locate and open the “admin.py” file inside the folder
  3. paste the code below:

Creating User Database Tables

We will not create any user database table as we will use the default Django User database table from django.contrib.auth.models                                                                                      

Create User APIs

These are the APIs to be used by the Django “users” app. Inside the “users” app folder create a folder called “api”. Create the following empty python files in it:

  • __init__.py – used to inform python that this is a python package or directory
  • serializers.py – used to create classes responsible for converting python database objects to JSON format using a built in Django rest framework class called serializers
  • views.py – used to create the user APIs
  • urls.py – used to create URLs that will redirect users to the appropriate user APIs inside the views.py file

Users project tree

serializers.py code

To do this:

  1. Open the “users” app folder
  2. Open the “api” app folder
  3. Locate/create a python filed labeled “serializers.py”
  4. We now create the serializer classes related to the Django built in User database model:

Modules to be imported

The modules to be imported that will be used are:

from django.contrib.auth.models import User –  The default Django user database table that will be used to create a new user

from rest_framework import serializers – The built in Django serializers method used to convert python database objects to JSON objects

To import the above methods, navigate into the “users” folder, into the “api” app folder and open or create a file labeled “serializers.py” and paste the code below:

UserCreateSerializer Class Logic

The UserCreateSerializer will be responsible for retrieving POST data passed to it and using that user data sent to create a new user in the database. It will have the following fields:

  • password2 – an extra field to create another password flied to be used for password confirmation

The class will interact with the User table and will require the data sent via POST to contain the email, password and password fields.

It will override the save method, so as to validate the confirmed password first before creating the new user. To create the above “UserCreateSerializer” serializer class in your project folder, navigate into the “users” folder, into the “api” app folder and open or create a file labeled “serializers.py” and paste the code below:

views.py code

To do this:

  1. Open the “users” app folder
  2. Open the “api” app folder
  3. Locate/create a python filed labeled “views.py”
  4. We now create the serializer classes related to the Django built in User database model:

Modules to be imported

The modules to be imported that will be used are:

  • from rest_framework.decorators import api_view, permission_classes –  api_view: Python decorator used to restrict a method’s access only via POST request and permission_classes: Python decorator used to set the permisions required to access a view method
  • from rest_framework.response import Response – The method will be used to send back HTTP response
  • from rest_framework.permissions import AllowAny – This method allows a view method to be accessed without providing authentication token or details
  • from .serializers import UserCreateSerializer- The serializer class that will be used to convert python database objects to JSON for transmition as a HTTP response
  • from rest_framework.authtoken.models import Token – The in-built django restframework table responsible for saving the user Tokens

To import the above methods, navigate into the “users” folder, into the “api” app folder and the file you created labeled “views.py” and paste the code below:

create_user API Logic

The API method responsible for registering a new user, below is its pseudocode steps:

  1. We will restrict this method to only be accessible via a POST method
  2. Allow this method to require no authentication for accessibility
  3. Pass the data sent with the POST request to the UserCreateSerializer
  4. The parameters passed should match the expected fields in the UserCreateSerializer
  5. Validate that the data passed has no errors
  6. Save the serialized data
  7. Generate the authentication token and send it to the user

Below is the code to paste inside the views.py file located in the folder location ”users/api/”:

urls.py code

These are the URLs that will be used by the user to navigate the “users/api” end points. To do this:

  • Open the “users” app folder
  • Open the “api” app folder
  • Locate/create a python filed labeled “urls.py”
  • Paste the code below:

Inside this urls.py is the log in API

Create Countries APIs

These are the APIs to be used by the Django “countries” app. Inside the “countries” app folder create a folder called “api”. Create the following empty python files in it:

  • __init__.py – used to inform python that this is a python package or directory
  • serializers.py – used to create classes responsible for converting python database objects to JSON format using a built in Django rest framework class called serializers
  • views.py – used to create the user APIs
  • urls.py – used to create URLs that will redirect users to the appropriate countries APIs inside the views.py file

Countries project tree

serializers.py code

To do this:

  1. Open the “users” app folder
  2. Open the “countries” app folder
  3. Locate/create a python filed labeled “serializers.py”
  4. We now create the serializer classes related to the Django built in User database model:

Modules to be imported

The modules to be imported that will be used are:

from countries.models import Continent, Country, Cities, API, Subscription –  The countries database tables or models we created in the countries’ “models.py” file

from rest_framework import serializers – The built in Django serializers method used to convert python database objects to JSON objects

To import the above methods, navigate into the “countries” folder, into the “api” app folder and open or create a file labeled “serializers.py” and paste the code below:

ContinentSerializer Class Logic

The Continent Serializer class will inherit the ModelSerializer class from the serializers package. It will have the following fields:

  • values– The JSON object to be returned will be labeled values, it will get its data from a class method called get_continent_values
  • get_continent_values – This method is responsible for returning the continent id and continent name

Inside this class will be a meta class, with two variables:

  • model – The serializer class will be set to get data from the Continent model.
  • fields – a list for us to set the class to return “values” variable as the desired response.

Below is the code to paste inside the serializers.py file located in the folder location ”countries/api/”:

CountrySerializer Class Logic

The Country Serializer class will inherit the ModelSerializer class from the serializers package. It will have the following fields:

  • values– The JSON object to returned will be labeled values, that will get its data from a class method called get_country_values
  • get_country_values – This method is responsible for returning the country id, country name and country code

Inside this class will be a meta class, with two variables:

  • model – We will set the serializer class to get data from the Country model.
  • fields – We then set the class to return values variable as the desired response.

Below is the code to paste inside the serializers.py file located in the folder location ”countries/api/”:

CitiesSerializer Class Logic

The Cities Serializer class will inherit the ModelSerializer class from the serializers package. It will have the following fields:

  • values– The JSON object to returned will be labeled values, that will get its data from a class method called get_cities_values
  • get_cities_values – This method is responsible for returning the cities name

Inside this class will be a meta class, with two variables:

  • model – We will set the serializer class to get data from the Cities model.
  • fields – We then set the class to return values variable as the desired response.

Below is the code to paste inside the serializers.py file located in the folder location ”countries/api/”:

APISerializer Class Logic

The A.P.I. Serializer class will inherit the ModelSerializer class from the serializers package. It will have the following fields:

Inside this class will be a meta class, with two variables:

  • model – We will set the serializer class to get data from the A.P.I. model.
  • fields – We then set the class to return the A.P.I. name and A.P.I. code as the desired response.

Below is the code to paste inside the serializers.py file located in the folder location ”countries/api/”:

SubscriptionSerializer Class Logic

The Subscription Serializer class will inherit the ModelSerializer class from the serializers package. It will have the following fields:

  • values– The JSON object to returned will be labeled values, that will get its data from a class method called get_subscription_values
  • get_subscription_values – This method is responsible for returning the subscribed A.P.I. id and A.P.I. name

Inside this class will be a meta class, with two variables:

  • model – We will set the serializer class to get data from the Subscription model.
  • fields – We then set the class to return values variable as the desired response.

Below is the code to paste inside the serializers.py file located in the folder location ”countries/api/”:

views.py code

To do this:

  1. Open the “countries” app folder
  2. Open the “api” app folder
  3. Locate/create a python filed labeled “views.py”
  4. We now create the serializer classes related to the Django built in countries database model:

Modules to be imported

The modules to be imported that will be used are:

  • from rest_framework import status –  This method is used to return back the HTTP response status of a request
  • from rest_framework.response import Response –  The method used to retunr back a response to the caller
  • from rest_framework.decorators import api_view, permission_classes –  api_view: Python decorator used to restrict a method’s access only via POST request and permission_classes: Python decorator used to set the permisions required to access a view method
  • from rest_framework.response import Response –  The method used to retunr back a response to the caller
  • from rest_framework.permissions import IsAuthenticated –  The class used to force a user to first authenticate by passing their token before getting access to the view’s data
  • from rest_framework.authentication import TokenAuthentication –  The class that states the type of authentication expected
  • from rest_framework.generics import ListAPIView –  A class used to return a list of python data objects
  • from countries.models import (Continent, Country, Cities, API, Subscription) –  The countries  database models or tables we created
  • from .serializers import (ContinentSerializer, CountrySerializer, CitiesSerializer, APISerializer, SubscriptionSerializer) – The serializers created to transform their related database python objects to JSON objects

To import the above methods, navigate into the “countries” folder, into the “api” app folder and open or create a file labeled “views.py” and paste the code below:

APIListView API Logic

The API method responsible for returning the list of APIs supported, below is its pseudocode steps:

  1. Fetch the api list data
  2. Pass the data sent with the POST request to the APISerializer
  3. Restrict the API to only be viewed by users who have authenticated
  4. State the authentication method expected to be a token authentication

Below is the code to paste inside the views.py file located in the folder location ” countries /api/”:

Subscription API Logic

The API method used by a user to subscribe to a particular A.P.I. for access, below is its pseudocode steps:

  1. This view method can only be accessed via a GET request
  2. A user is required to authenticate, by passing their token with the header
  3. Try getting the specific API a user wants to subscribe to, if the API record does not exist, send back a HTTP 404 error
  4. Pass the user and the requested API to the subscription model for subscription
  5. If a user already subscribed or a new subscription has been made inform the user appropriately

Below is the code to paste inside the views.py file located in the folder location ” countries /api/”:

Get Subscriptions API Logic

The API method responsible for returning the APIs a user has subscribed to, below is its pseudocode steps:

  1. This view method can only be accessed via a GET request
  2. A user is required to authenticate, by passing their token with the header
  3. Try getting all subscriptions related to the user, if the subscription data does not exist, return a HTTP 404 error
  4. Else if the data exists, pass the python database objects to it is serializer for convertion to JSON objects
  5. Invoke the response class to return the JSON subscription objects

Below is the code to paste inside the views.py file located in the folder location ” countries /api/”:

Unsubscribe API Logic

The API method responsible for unsubscribing a user from an API, below is its pseudocode steps:

  1. This view method can only be accessed via a DELETE request
  2. A user is required to authenticate, by passing their token with the header
  3. This view is used by a user to unsubscribe from an API, it expects the API id as a parameter
  4. Using the API id passed and the authenticated user try getting the subscribed API from the subscription table
  5. If the subscription data does not exist, return a HTTP 404 error
  6. If the subscription exists, delete it and inform the user appropriately
  7. Invoke the response class to return the JSON subscription objects

Below is the code to paste inside the views.py file located in the folder location ” countries/api/”:

Get Continents API Logic

This view is used by a user to access the continents API data, below is its pseudocode steps:

  1. This view method can only be accessed via a GET request
  2. A user is required to authenticate, by passing their token with the header
  3. We first try to confirm if the authenticated user has subscribed to use this A.P.I. if not send back a HTTP 404 error
  4. If the user is authorized to access the continents API, get all continents
  5. If the continent data does not exist, return a HTTP 404 error
  6. Else if the continent data exists, pass the python database objects to it is serializer for conversion to JSON objects
  7. Invoke the response class to return the JSON continents objects

Below is the code to paste inside the views.py file located in the folder location ” countries/api/”:

Get Country API Logic

This view is used by a user to access the country’s API data, it expects the continent id as a parameter, below is its pseudocode steps:

  1. This view method can only be accessed via a GET request
  2. A user is required to authenticate, by passing their token with the header
  3. We first try to confirm if the authenticated user has subscribed to use this A.P.I. if not send back a HTTP 404 error
  4. Using the continent id, we will get the specific continent
  5. If the continent does not exist, return a HTTP 404 error
  6. Using the returned continent, we will get the specific countries related to the continent
  7. If the countries do not exist, return a HTTP 404 error
  8. Else if the countries data exists, pass the python database objects to it is serializer for conversion to JSON objects
  9. Invoke the response class to return the JSON countries objects

Below is the code to paste inside the views.py file located in the folder location ” countries/api/”:

Get Cities API Logic

This view is used by a user to access the cities’s API data, it expects the country id as a parameter, below is its pseudocode steps:

  1. This view method can only be accessed via a GET request
  2. A user is required to authenticate, by passing their token with the header
  3. We first try to confirm if the authenticated user has subscribed to use this A.P.I. if not send back a HTTP 404 error
  4. Using the country id, we will get the specific country
  5. If the country does not exist, return a HTTP 404 error
  6. Using the returned country, we will get the specific cities related to the country
  7. If the country do not exist, return a HTTP 404 error
  8. Else if the cities data exists, pass the python database objects to it is serializer for conversion to JSON objects
  9. Invoke the response class to return the JSON cities objects

Below is the code to paste inside the views.py file located in the folder location ” countries/api/”:

urls.py code

These are the URLs that will be used by the user to navigate the “countries/api” end points. To do this:

  • Open the “countries” app folder
  • Open the “api” app folder
  • Locate/create a python filed labeled “urls.py”
  • Paste the code below:

Apply Database Changes

  1. In your terminal ensure you have activate your project’s virtual environment
  2. While in your projects activated virtual environment in your terminal
  3. Create database changes to be made by typing in the terminal the command: python manage.py makemigrations
  4. Apply database changes by typing in the terminal the command: python manage.py migrate
  5. Create a super user by typing the command: python manage.py createsuperuser
  6. Enter the username
  7. Enter the email
  8. Enter the password
  9. Remember these superuser credentials, they will be need when logging into the Django admin interface

Configure Project URLs

This is where the URLs that point to each Django app are placed so that they are accessible from a browser. They are usually placed in a file called “URLs.py”. Do the following to create/edit this file:

  1. Open your Django project folder: “djangorestapis”
  2. Locate a folder with a similar name to your Django project folder, this folder is in the same directory as your “countries” app folder
  3. Open the “djangorestapis” folder that is inside Django project folder
  4. Locate/create a python file labeled “URLs.py”
  5. Paste the code below

Project Tree

Below is a screenshot of how your project tree should look like, assuming the name of your Django project is “djangorestapis”:

Run the server

  1. cd/navigate into the “djangorestapis” Django project via the terminal
  2. Activate the virtual environment by typing the command: “venv\Scripts\activate”
  3. Start the server by typing the command: python manage.py runserver
  4. If there’s nothing wrong, the server should be up on http:127.0.0.1:8000/admin
  5. We will now initialize the system, below is how to do so

Initializing the system

  • Here we will put data into the system. Below are the steps on how to do so.
  • While on the Django admin page: http:127.0.0.1:8000/admin
  • Log in using the super user credentials we created here
  • You will be taken to the Django page below:
  • On the left side of the page are the database table and the right side are any recent actions performed
  • We will start by adding APIs to the API table, click on the APIs link under countries to do so, you will be redirected to the page below:
  1. Click on Add to add an A.P.I
  2. The first API to add is countries, enter the name “Countries” and code “CNT”. This means that countries will have an A.P.I id of 1
  3. Click on ‘Save and add another button”
  4. The second API to add is continents, enter the name “Continents” and code “CON”. This means that continents will have an A.P.I id of 2
  5. Click on ‘Save and add another button”
  6. The third API to add is cities, enter the name “Cities” and code “CIT”. This means that cities will have an A.P.I id of 3
  7. Click on “Save”
  • We will now enter the continents data, click on the continents link on the left side navigation bar and enter a continents name and code, save and another.
  • We now enter the countries data, click on the countries link on the left side navigation bar and enter a countries name and code, save and another
  • We now enter the cities data, click on the citiess link on the left side navigation bar and enter a the cities linked to a particular country, save and another
  • We will finally create a token for the super user, click on the tokens link on the left side navigation bar under the Auth Token label
  • Click on “Add Token” select the super user from the dropdown and save.

API Endpoints Table

APIEndpoint
Create or Register New User IDhttp://127.0.0.1:8000/api/users/create
Log In APIhttp://127.0.0.1:8000/api/users/login
Get all system APIs and their idshttp://127.0.0.1:8000/api/
Subscribing to an APIhttp://127.0.0.1:8000/api/subscribe/api_id /
Unsubscribing from an APIhttp://127.0.0.1:8000/api/unsubscribe/api_id/
Subscribed APIshttp://127.0.0.1:8000/api/subscribed/
Get Continents APIhttp://127.0.0.1:8000/api/continents/
Get Countries APIhttp://127.0.0.1:8000/api/country/continent_id/
Get Cities APIhttp://127.0.0.1:8000/api/cities/country_id/

Testing the System

  • Download Postman
  • Open Postman
  • On the top right menu select File then select New to create a new HTTP request
  • A new window will pop up, where you then select HTTP Request

After selecting the HTTP Request you will be redirected to the page below

  • To register: paste the API to create or register a new user so as to get the token on the text field next to the GET request drop down, but first change the GET drop down to POST
  • Below the POST request drop down are tabs, select the Body tab
  • While in the body tab select form-data
    • Enter the key email and its value
    • Enter the key password and its value
    • Enter the key password2 and its value
    • Click the send button, you will get a reply back with the token e.g “cf583d742375526cbf1826bf51d54603a9712f49”
    • Below is a screenshot
  • To login: paste the login API on the text field next to the GET request drop down, so as to get the token, but first change the GET drop down to POST
    • Below the POST request drop down are tabs, select the Body tab
    • While in the body tab select form-data
    • Enter the key username and its value
    • Enter the key password and its value
    • Click the send button, you will get a reply back with the token
    • The token returned is the token to be placed on the header with the key “Authorization” and value as “Token cf583d742375526cbf1826bf51d54603a9712f49”
    • Below is a screenshot
  • To test the core APIs i.e. Continents API, Country API, Cities API, Subscribe API, Unsubscribe etc.
    • Create a new HTTP request
    • Select the request type from the GET request drop down
    • Below the selected request drop down is the “Headers” tab
    • Select the “Headers tab”
    • Under Key enter the value “Authorization”
    • Under value enter the token in the following format “Token cf583d742375526cbf1826bf51d54603a9712f49”
    • Click on send to view data
    • Below is an example using the continents API

Conclusion

You should now have a basic understanding of how to create a restful API platform in Django.

Further improvements could be done on the project such as, tracking the number of times a user has called a subscribed API or sending better or refined error messages to a user instead of HTTP 404 error messages

Finally, you can find the code snippets in this @repo.

Quick Guide

If you just want to clone the project and get it up running, below is how to do so in minutes:

  1. Clone it:
    • git clone https://bitbucket.org/dans0l/djangorestapis.git
  2. Cd into it:
    • cd djangorestapis
  3. Create a venv:
    • python3 -m venv venv
  4. Activate venv:
    • Mac/Linux: source venv/bin/activate
    • Windows: venv\Scripts\activate
  5. Install the requirements:
    • pip install -r requirements.txt
  6. Create DB
    • python manage.py makemigrations
  7. Apply DB Changes:
    • python manage.py migrate
  8. Create a super user by typing the command
    • python manage.py createsuperuser
    • Enter the username
    • Enter the email
    • Enter the password
    • Remember these superuser credentials, they will be need when logging into the Django admin interface
  9. Run the server:
    • python manage.py runserver
  10. Navigate to the site: http://127.0.0.1:8000/admin
  11. Navigate to this article’s section called “Initializing the system” to know how to set up data in the system, then navigate to this article’s section called “Testing the System” to know how to test the APIs

Please let me know how your experience was, Thank you.

0 Shares:
You May Also Like