Create a simple REST API with Django

  • 2020-03-10 08:04 AM
  • 83

In this article, we will be building a simple API with one endpoint that sends a response "Welcome to the BookStore" when a GET request is made to the server. The purpose is to show the bare minimum setup you need to get a Django REST API up and running.

Requirements

  • Basic Knowledge of Python programming language.
  • Python: To be able to run python(.py) files on our machine, we need to have the python compiler installed on our computer. The version should be a python3 version, you can check out the Python to download. To check if you have python installed:
$ python3 --version

  • Pipenv: Pipenv is a packaging tool for Python that solves some common problems associated with managing your Python dependencies. For more info, check out Pipenv. To check if you have pipenv installed:
$ pipenv --version

Let’s get started!! 😀

First, let’s create a directory for our app then change directory into the new folder:

$ mkdir bookstore
$ cd bookstore

Next, we’ll spin up an environment using pipenv:

$ pipenv shell

If your environment was started correctly, depending in the terminal you are on, it will look something like this:

(env-name) [email protected]:~/Documents/bookstore$

For us to build an app using Django we have to install the Django framework in our environment:

$ pipenv install django 

Next, let’s create our Django Project. We’ll use the django-admin tool which will generate the project folder, basic file templates, and project management script (manage.py).

$ django-admin startproject bookstore_app

Voila!! 🤩, that’s all you need to have a Django server running. So to test the server, we’ll change directory into the newly created Django project and run the server.

$ cd bookstore_app
$ python manage.py runserver

To see all the possible scripts you can use on the manage.py file, in the project directory run:

$ python manage.py --help

If you are using a zsh terminal, double-tap the TAB key after typing python manage.py. It prints a more descriptive list of available scripts.

Now that we have Django server ready, it’s time to set our server up to be able to respond to requests and to do this we’ll be using the Django Rest Framework.

Let’s add this powerful toolkit to our environment:

$ pipenv install djangorestframework

One thing I love about Django is that it encourages breaking our web app
components into separate applications, which could be re-used in different projects if need be. I prefer to call it Plug 'n' Play😀. Now, let’s create an app called api where we will be coding up the different endpoints for this project (but we are concerned with one for now 😀). We’ll be utilizing the manage.py file already generated when we created a project.
N/B: The name of the app could be anything, so long as they are not reserved words.

To create an app, run:

$ python manage.py startapp api

This generates a folder api in the project folder bookstore_app that contains some boilerplate files and code. Now, we have to make the project aware of the new app we just created and the Django Rest framework toolkit we installed earlier.
To do this, we’ll open the settings.py file in the project directory bookstore_app and add the name of the app api and rest_framework to a list of already existing app INSTALLED_APPS.

# ./bookstore_app/settings.py
...
INSTALLED_APPS = [
    ...
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'api',
    'rest_framework',
]

Now we are at the point of creating some views. On the views.py file in the api app, we’ll be writing out the functionality GET request to return with a response "Welcome to the BookStore!".

# ./bookstore_app/api/views.py

from django.http import JsonResponse
from rest_framework.decorators import api_view

@api_view(["GET"])
def welcome(request):
    content = {"message": "Welcome to the BookStore!"}
    return JsonResponse(content)

That is all with the functionality, w are just left with adding the api app URLs to the project bookstore_app URLs. First, let’s add a url that will call on this function we just created.

Let’s create a urls.py file in the api folder

$ cd api
$ touch urls.py

In the api/urls.py file, let’s add the welcome path

# ./bookstore_app/api/urls.py

from django.urls import include, path
from . import views

urlpatterns = [
  path('welcome', views.welcome)
]

And also, include the api URLs in the project’s URLs

# ./bookstore_app/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('api.urls')),
]

Annnnnnnndddd!!! We are done!! 🕺💃

Before we get the server started, let’s run migrations first.

$ python manage.py migrate

Now the migration is done, let’s fire up the server 🚀

$ python manage.py runserver

To test, make a GET request to the server on Postman with URL http://127.0.0.1:8000/api/welcome or visiting the URL on the browser.

I am really glad you got to this point. At this point, our server does not do much. Next, we will be adding authentication to our server.

Thank you for reading 😀

Suggest