Building a Fully-Functioning API with Django and and Sharing on RapidAPI (Part -2)

•

Fri Mar 31 2023

•

9 min read

Let's learn the process of developing an API in Django using the Django REST Framework.

This guide's first part covered the process of setting up Django API and Django REST Framework, including installing dependencies, adding data through a Django web application, and creating endpoints.

In this guide, we will deploy the Django API on Heroku. Heroku is a cloud-based platform for building, deploying, and managing web applications. It supports multiple programming languages and provides various tools and services, such as databases and add-ons.

The first step is to check if two Python libraries are installed by running the following command on the command prompt:

pip install gunicorn django-heroku

Next, create a new file in the project's root directory in VS Code and name it "runtime.txt." In this file, specify the Python version you want to use (in this case, 3.8.1) and save it.

python-3.8.1

After that, create another file in the root directory and name it "Procfile." This file doesn't have a file extension like "runtime.txt", and it should contain only one line:

web: unicorn djangorapidapi.wsgi:application --log-file=/path/to/log/file.log

Before proceeding, let's modify the "runtime.txt" file by updating the previous version of Python (3.8.1) to the latest version, which is 3.9.0.1. This is necessary because using an older version can sometimes lead to stack errors we would like to avoid.

To generate a requirements file, run the following command in the command prompt:

pip freeze > requirements.txt

This will create a "requirements.txt" file in your project directory that contains all the libraries and frameworks used in your project.

Developing Heroku database for our Django Project

In this step, we need to import django_heroku in the settings.py file to use it with our project's database.

Additionally, we also need to import dj-database_url. We can change the DATABASES configuration and then add a code block to the bottom of the file. This will allow us to use the Heroku database for our Django project.

py
from pathlib import Path
import django_heroku
import dj_database_url
# Build paths inside the project like this: BASE_DIR / 'subdir'
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings unsuitable for production
# see https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-)u%igrqo6$s b3I%m(h%4l jehnkkq5ues)lbzm9(z=7zm-htk'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'apiapp'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'yourproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DATABASES = {
'default': dj_database_url.config()
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Rest Framework
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
}
django_heroku.settings(locals())

The following command logs into Heroku through the command prompt:

heroku login

After running this command, a page will be opened in the default browser prompting you to log in to Heroku. Once you log in through the browser, you will also be logged in through the terminal.

Creating a new app on Heroku

The next step after creating a new app on Heroku is to initialize a new git repository, add our code to the repository, and push it to Heroku. Here's how to do it:

  • Initialize a new Git repository:
git init
  • Add your code to the Git repository:
git add .
  • Commit your code:
git commit -m "Initial commit"
  • Add the Heroku remote to your Git repository:
heroku git:remote -a django-rapid-api
  • Push your code to Heroku:
git push heroku master

After running these commands, your code will be deployed to Heroku and you can access your app by going to the URL provided by Heroku.

Let's create a new add-on for our database using PostgreSQL on Heroku. This will create a new Heroku Postgres add-on with the Hobby Dev plan attached to our app.

heroku addons:create heroku-postgresql:hobby-dev

A new PostgreSQL database has been created, and we can push our codebase to the Heroku app. To do this, we can use the following command after adding and committing our changes:

git push heroku master

The deployment process to Heroku was successful, and the API can be accessed using the link "heroku://django-rapid-api.herokuapp.com/".

Before deployment, migrations need to be run, which can be done by executing the following command:

heroku run python manage.py migrate

After running the above command, the database migrations will be applied, and we can use the API.

Deploying app on Heroku

To address the issue of our API not returning any data, let's revisit the link "heroku://django-rapid-api.herokuapp.com/ deployed to Heroku" on our browser. We can see that the API has been successfully deployed, but no data is being returned.

To resolve this, let's create a super user to log in online and add some data to our database. To create a superuser, we can execute the following command in our terminal:

heroku run python manage.py createsuperuser

When prompted, we can bypass the password validation and create the user by typing "y". This will create a superuser with the specified username and password. We can then go to the admin panel of our deployed app by navigating to "heroku://django-rapid-api.herokuapp.com/admin" in our browser.

Here, we can log in with the superuser credentials we just created, which are "admin" for both the username and password.

After logging in, we can add three students to the database: Tim, Tom, and Jim, ages 27, 16, and 19, respectively. This means that our database now contains three objects.

When we visit "http://heroku://django-rapid-api.herokuapp.com" again, we can see that all the values and data we added are being returned successfully.

HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "name": "Tim", "age": 27 }, { "name": "Tom", "age": 16 }, { "name": "Jim", "age": 19 } ]

This indicates that our API is working perfectly. We created the API on our local machine and then hosted it on Heroku, which is now accessible through a URL.

Testing by leveraging Paw

Before proceeding, we will test our API using an online testing tool called Paw. This tool is used to test APIs. To test our API, we can input the API link in the GET search, which will send a response.

Let's test our API by navigating to the endpoint "heroku://django-rapid-api.herokuapp.com" in the GET search and clicking send. We can see a 200 OK response, meaning our API is online and working correctly.

Publishing it on RapidAPI

By now, we have developed a basic Django API using the Django Rest Framework and have successfully deployed it to Heroku. We now have the link to the API, which we can use to integrate with RapidAPI.

RapidAPI is a platform that provides various APIs that can be easily integrated into applications; for example, if you want to send an email using an API, you can use SendGrid.

Loading component...

Once you have completed the registration, click on the "Add New API" button and enter the necessary details.

As an illustration, you can give your API a name like "Test" and a summary such as "this is only for testing." Then, select "Data" as the category and pick "UI" as the data type. Hit the "Add API" button to establish your new API.

To provide more details about your API on RapidAPI, add a long description such as "I created this API for tutorial purposes only" and provide the website URL as "heroku://django-rapid-api.herokuapp.com/".

You can also select the "Data" category and save your changes. While you can upload an image, it is not mandatory. Once you have updated your API, the changes will be reflected on RapidAPI.

Next, we will add additional endpoints to our API. If you have been following this guide, you will know that we have already created two endpoints. We will name the first endpoint "Home" and provide a description indicating that it will return data when accessed using a GET method.

Once we have saved this endpoint, we will create another one.

To add another endpoint, we can name it "Second" with a description of "does the same as the home endpoint". In the GET search, we can enter "/second-endpoint" and fill out the rest of the information like before.

Then, we can click "Save" to add the second endpoint. Now we have two endpoints created.

To make our API public on RapidAPI, we need to add the base URL "heroku://django-rapid-api.herokuapp.com/" and save the changes. Then, we can switch the button to make the API public. It may take a few seconds to load all the changes.

Testing API

We can easily test our API directly from the RapidAPI platform to see the results. By doing so, we can view all the data stored in our database.

Additionally, we can add a new student's information in our Django administration and then resend a query to see if the data updates.

Wrap up

We have successfully built a Simple Django API using the Django Rest Framework and deployed it to Heroku. We then added our API to the RapidAPI platform, making it accessible to anyone who wants to use it.

With RapidAPI's vast collection of APIs, our API can be easily discovered by others who may find it useful. We also tested our API directly from the RapidAPI platform, and any changes we make to the database will be reflected in the API.

Overall, this process has shown how easy it is to create and share APIs using modern web development tools and platforms.