DEV Community

Cover image for Create a simple API using Django Rest Framework in Python

Posted on

Create a simple API using Django Rest Framework in Python


Django Rest Framework is a powerful library that sits on top of existing Django projects to add robust web APIs.

REST is an "architectural style' that basically exploits the existing technology and protocols of the web.

API a set of rules and mechanisms by which one application or component interacts with the others.

In this tutorial we’ll create a basic Django ToDo app and then convert it into a web API using serializers, viewsets, and routers.

Complete source code is available on Github .

1.Initial setup

Will commence by executing the following in the command line;

    $ cd ~/Destkop
    $ mkdir todo && cd todo
    $ pipenv install django==2.2.5
    $ pipenv shell
    (todo) $ django-admin startproject todo_project .
    (todo) $ python startapp todos

We've used pipenv to install django and started both a django project (todo_project) and an app(todos).
Now we need to update our app in the settings file.

       # todo_project/

Perform our first migration to set up the initial database at this point.

       (todo) $ python migrate


We create a basic model for our Todo app database.

       # todos/
       from django.db import models

      class Todo(models.Model):
          title = models.CharField(max_length=200)
          description = models.TextField()

         def __str__(self):
            return self.title

Makemigrations for the project database to the Server.

      (todo) $ python makemigrations todos
      (todo) $ python migrate

Register the app on the admin file to showcase the models on the server dashboard.

     # todos/
     from django.contrib import admin

     from .models import Todo

In a normal Django app at this point we would need to add urls, views, and templates to display our content. But since our end goal is an API that will transmit the data over the internet, we don’t actually need anything beyond our file!

Lets create a superuser to act as an ADMIN and then power off the django project to the server.

     (todo) $ python createsuperuser
     (todo) $ python runserver

Navigate to and log in with your new superuser account.

Django Admin Dashboard

Click on Todos and add your entries.I added the following;

      1st todo = Learn DRF
      2nd item = Learn Python too

Entries for Todo app

Now it’s time to use Django Rest Framework.

Part 2.....

Top comments (0)