Django as an API.
I have built a few applications using Rails as my own API. Creating my own backend API is something I really enjoy as as the programmer, it’s something that I get to have full control over. I don’t have to worry about some other random database out there and having to adjust my frontend to worry about it, although that’s really not that much of a problem. Rails is a great tool to build out the backend of a project, but Django can do the same. Having never done it before, I found it surprisingly easy to setup and manage. In this post I’m going to go over how to set up Django for the backend of the project.
The way to start any Django project is to first create a virtual environment. This is not required but highly recommended as it will keep all your dependancies within the environment as opposed to globally. Once you have opened up the text editor of your choice, the steps to create and activate a virtual environment are as follows:
pip install virtualenvvirtualenv venv //this second part is where you can name your environment, name it anything you want. I just prefer venvsource venv/bin/activate //this is the command to activate the virtual environment. The command is different depending on mac or windows so always check.
Once the virtual environment has been activated. Django can be installed and created.
pip install djangodjango-admin startproject backend //again the project name can be whatever you want. If I use it for a backend, that's what I prefer to call it.
Once your project is finished building, you can cd into it and start creating apps for your backend. In this example, we’re going to build a simple todo app that will coordinate with React on the front end. Once the app is created, migrations will have to be run and the server will be started.
python manage.py startapp todopython manage.py migratepython manage.py runserver
Django servers run on localhost 8000, you can navigate over to that page to confirm that it worked.
The next step is to open up your settings.py file and register the todo app under the INSTALLED_APPS section, simply add ‘todo’ or whatever you decided to name your app.
The next step is to build out the model for the todos. Here is where you can give your models any field you want. It allows you to be very creative and decide what the user experience will be like. In this case, we won’t go too extreme. But the possibilities are endless.
from django.db import models# Create your models here.class Todo(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()def _str_(self):
return self.title
Each class extends from models.Model. You can see that each todo will have a title and a description. The title will be represented by a character field and maxes out at 120 characters. The text field for the description means that we can have quite a lot of text for our todo description, whether we use all of it or not. The self method simply returns the title of the todo as a string.
Migrate the changes:
python manage.py makemigrationspython manage.py migrate
To add admin functionality, which will make managing the backend much easier. First register the app in the admin.py file located within any app that you have created.
from django.contrib import adminfrom .models import *# Register your models here.admin.site.register(Todo)
What’s next is where the real magic happens! Django had the amazing admin functionality that allows an admin (that’s you) to add, change, and modify your models incredibly easy. This is great database management and to enable this, we need to create a superuser!
python manage.py createsuperuser
After typing this command, you will have to input a username, email, and password which you will use when you navigate to http://127.0.0.1:8000/admin/
Having admin functionality for your models makes it incredibly easy to change and update any of the fields you had when the class was created.
Now that our todo model has been created, we need to setup the API.
We’ll need to install djangorestframework and django-cors-headers
pip install djangorestframework django-cors-headers
Both rest_framework and corsheaders will need to be added to the INSTALLED_APPS section of your settings.py file. in MIDDLEWARE, add:
'corsheaders.middleware.CorsMiddleware'
Cors-headers is a Python library that prevents errors due to CORS rules.
In order for the frontend to work with the data, it needs to be converted to JSON. This is done with the use of serializers. If we go into the todo folder and create a serializers.py file, we can add the following code:
from rest_framework import serializers
from .models import Todo
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = ('id', 'title', 'description')
This code specifies the model to work with and the fields that need to be converted to JSON.
The next step is to create the View, in the todo folder, open the views.py file and add the following code:
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import TodoSerializer
from .models import Todo
# Create your views here.
class TodoView(viewsets.ModelViewSet):
serializer_class = TodoSerializer
queryset = Todo.objects.all()
Using viewsets provides the ability to perform CURD (Create, Read, Update, Destroy) operations automatically.
The last thing we need is the URL path for the API. Open the urls.py file in the todo folder add the following to the url patterns:
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from todo import views
router = routers.DefaultRouter()
router.register(r'todos', views.TodoView, 'todo')
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(router.urls)),
]
This allows the API to access the todos as a whole, or access a single one in order to update or delete them. With all the CRUD operation enabled and defined, our backend is now complete!
Django makes it very easy to create you own API through the admin functionality and installing the rest framework. Use whatever frontend language you want to fetch the data so the user can interact with it. This makes it very easy to have control over your data which in turn makes your job much easier.