Building an API with Django REST Framework 1: Getting Started

Zeba Rahman
fabcoding
Published in
6 min readMar 28, 2019

Installing Django

To install django, go to your terminal or command line and run these.

pip3 install django
pip3 install djangorestframework

Creating a new project

Navigate to your workspace folder, and run this command

django-admin startproject api

Where obviously, api is the name of your project. It can be anything you choose. Navigate to your project folder.

cd api

You’ll see a structure like this

api
-- manage.py
-- api
-- -- __init__.py
-- -- settings.py
-- -- urls.py
-- -- wsgi.py

manage.py is the file that accesses the db, creates users for databases. Do not edit this file.

init file tells your computer to treat the folder as a python package.

The parent folder and child folder both have the same name api. So to avoid confusion, rename the parent folder as my_project. So now your structure is like this

my_project
-- manage.py
-- api
-- -- __init__.py
-- -- settings.py
-- -- urls.py
-- -- wsgi.py

Now you have the base project. Let us run it. Make sure your command is in my_project. Type this command

How to run the server

python3 manage.py runserver

You’ll see a message like

Starting development server at http://127.0.0.1:8000/

Open this URL into your browser and you should see this.

http://127.0.0.1:8000/ or http://localhost:8000/admin

To exit the server, go back to terminal and press CTRL+C.

I recommend bookmarking that link since you will be going to that URL a lot, making changes and testing it. You would ideally always leave the server running, and make changes into your code and save, and the server automatically reflects the changes. You don’t need to restart the server every time.

Now you have created a base Django project. Next, we shall set up the database.

Creating your first app

What is an app in django? Simply stating, every separate section/module in your website will be an ‘app’. A news feed section, will be one app. A forum, a second app, a videos section, a third app, a profile section, a fourth app, and so on; and all these apps would communicate with each other to achieve the tasks. Apps help you organize the different parts of your website or API. If an app is managing many things, you need to break it up into different apps; such that every app manages one task.

To create an app, simply type the command. Make sure you are in the parent project folder which has manage.py. Here we are naming our first app as userapi. In the next tutorial we will be using this app to manage user registration, login, authentication, authorization; etc.

python3 manage.py startapp userapi

Check your project folder, you should see a new folder named userapi. Django creates all the necessary files required for the basic app. Let’s go through the files.

userapi
-- __init__.py
-- admin.py
-- apps.py
-- models.py
-- tests.py
-- views.py
-- migrations

Create just one more file here named:

-- urls.py

With the following content.

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

urlpatterns = [
]

init.py just indicates that the folder is not a normal folder, rather it’s a python package. apps.py is basically a settings file for the app. admin.py is for creating an admin panel which a lot of websites have. urls.py defines the urls inside the app module.

models.py is a blueprint for your database. We define the tables and schema here.

tests.py is for creating tests for your app.

views.py are just python functions, that take a user request and gives them some response. Mostly, they take requests of URL routes and send back a webpage, or sometimes it can send a logout or login function, etc. These will be discussed later in detail.

Let us add the app to our main project. Open your settings file, api/settings.py. Find The Application definition section and add ‘rest-framework’ and ‘userapi’ to it. Whichever apps you create, you will need to add it here.

# Application definition

INSTALLED_APPS = [
...
'rest_framework',
'userapi'
]

Furthermore, open the api/urls.py file and add URLs for the userapi app;

from django.contrib import admin
from django.urls import path, include
from django.conf.urls import include, url
urlpatterns = [
path('admin/', admin.site.urls),
path('userapi/', include('userapi.urls')),
]

This ‘path’ defines an ‘admin’ route to your website. It is responsible for loading a view when you open the website URL appended with the given path. the path(‘admin/’, admin.site.urls) is responsible for loading the admin page when you open http://localhost/admin URL.

Set up database

First. we need to install psycopg2.

pip3 install psycopg2

We will be using PostgreSQL database, instead of the default sqlite, since it is more robust and you will never have to migrate to another database.

Download PostgreSQL from this link. Install it and note your superuser password and port number. By default the port number is 5432.

Open the pgAdmin4 application/tool that came with the PostgreSQL package that you just installed.

Create a new database, by right-clicking on databases in the left pane, and selecting Create.

We will name our database as my_api_db. Enter the name and click on save.

Go to your project settings.py file. That is, api/settings.py. Scroll down to database section. You’ll see this

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

Change the parameters to this:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'my_api_db',
'USER': 'postgres',
'PASSWORD': 'admin',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}

Set the credentials accordingly. NAME is the name of db that you created. “postgres” is the default superuser, that was also selected while creating the new database. The host is localhost for now. Later when you deploy it, this will be changed. The password should be the password that you entered for the superuser account while you were installing PostgreSQL. PORT is the port number you saved while installing, if you did not specifically change it, it should be 5432.

Now it’s time to make initial migration of the database. Before you do this, remember that changing the base user model in django after the initial migration, is very difficult. So, it is best to create a custom user model at this step before initial migration, so that you can customise it later however you want. So this custom model step is optional but highly recommended.

We shall create our custom user model in our userapi app. Go to userapi/models.py and add this.

from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
pass

Then go to api/settings.py file and register this as the user model to be used by Django, by adding this line.

AUTH_USER_MODEL = 'userapi.User'

Lastly, go to your terminal, in your main project folder (which contains manage.py file), and run the following command.

python3 manage.py makemigrations

Next, run this command.

python3 manage.py migrate

This will create the initial tables for our Django application. Next, create an initial user for your Django website.

python3 manage.py createsuperuser

Enter username, email, password and you’re done. Let’s test it. Run the server using:

python3 manage.py runserver

Go to browser and open

http://localhost:8000/admin

Login with the new superuser account that you just created from the terminal. You should see the default Site administration panel.

Next steps

In part 2 of this tutorial, we shall continue with our userapi app and implement authentication & authorization, and create endpoints for user login, register, logout etc.

Originally published at Fabcoding.

--

--