DEV Community

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

Posted on

Create a simple API using Django Rest Framework in Python

Intro

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 manage.py 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/settings.py
       INSTALLED_APPS = [
              ...
       'todos.apps.TodosConfig',
        ]

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

       (todo) $ python manage.py migrate

2.Models

We create a basic model for our Todo app database.

       # todos/models.py
       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 manage.py makemigrations todos
      (todo) $ python manage.py migrate

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

     # todos/admin.py
     from django.contrib import admin

     from .models import Todo

     admin.site.register(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 models.py file!

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

     (todo) $ python manage.py createsuperuser
     (todo) $ python manage.py runserver

Navigate to http://127.0.0.1:8000/admin 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)