Simple RESTful API With Python and Django

by desaisam7 in Circuits > Software

47 Views, 1 Favorites, 0 Comments

Simple RESTful API With Python and Django

Screenshot 2024-10-25 131317.png

In this tutorial, you will learn how to create a simple RESTful API using Python and the Django framework. A REST API allows different systems to communicate using HTTP(S) requests. We will use Django Rest Framework to simplify the process and create a quick but effective CRUD (Create, Read, Update, Delete) API. The end point we create in this guide will simply append text to the text sent in our post request.

Supplies

Prerequisite Knowledge

  1. Basic Programming Experience
  2. Basic Terminal/CMD use
  3. Understanding Client/Server relations

Environment Setup

  1. Python 3.X.X Installed (Python Installation Guide)
  2. Pip Installed (Pip Installation Guide)
  3. VS Code or equivalent IDE

Warnings

  1. Don't hard close the server - use CTRL + C to close the server. If the terminal is forced closed, this can allow background processes to continue running.
  2. Require Authentication - in a production environment, endpoints should not be exposed to the internet without some form of authentication. This guide does not cover adding security to endpoints.

Setting Up Your Django Project

Screenshot 2024-10-17 113937.png

Initialize the Django project using these terminal commands

Create the project: django-admin startproject myproject

***If this returns an error try python -m django startproject myproject

Enter the project directory: cd myproject

Start the server: python manage.py runserver


At this point, you should see a message saying the development server is starting.

Set Up Django REST Framework

At this point, its assumed that the Django Rest Framework is installed. If not, install it using pip install djangorestframework.


Now that the library is installed, to use it, navigate to myproject/settings.py and add 'rest_framework' to the INSTALLED_APPS section. See the code snippet below.


INSTALLED_APPS = [
...
'rest_framework',
]

Create Models

Screenshot 2024-10-17 120503.png

Models dictate what types of parameters are going to be passed into an endpoint. One model can be applied to many endpoints, or each endpoint could have its own model depending on the use case.


First, we are going to need to create a new directory called 'myapp'. This folder should be on the same level as the 'manage.py' file. See the above image. This directory will also need to be added to the 'INSTALLED_APPS' in settings.py similar to how we added rest_framework.


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

To create the model, we want to create a file called 'testmodel.py' in the 'myapp' directory. The contents of this file can be seen below. For this example, we are going to create one model that takes in a simple parameter called 'text'.

from django.db import models
class TestModel(models.Model):
text = models.CharField(max_length=100)
def __str__(self):
return self.name

Creating a Serializer

Similar to models, each endpoint needs to be assigned a serializer. A serializer converts data into a format that can be easily sent over the web. In the 'myapp' directory create a file called serializers.py. Lastly, create a serializer for the TestModel model.

from rest_framework import serializers
from .models import *
class ItemSerializer(serializers.ModelSerializer):
class TestModelSerializer:
model = TestModel
fields = '__all__'

Creating Views

Views are where the function to be called at each endpoint is written. Create a file called views.py in the 'myapp' directory. A basic blank endpoint with no functionality can be seen below.

from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
from .serializers import ItemSerializer
class ItemViewSet(APIView):
queryset = TestModel.objects.all()
serializer_class = ItemSerializer


Of course, we want to actually do something when an endpoint is called. For example, if we wanted our endpoint to take in the text from earlier and add data to it we could do the following.

class ItemViewSet(APIView):
def post(self, request, *args, **kwargs):
# Extract 'text' from request body
text = request.data.get('text', '')
# Append the string to 'text'
updated_text = text + " Adding Data To string"
# Return the updated string in the response
return Response({"updated_text": updated_text})

Set Up URLS

Now we need to link the API views to URLs. In myapp/urls.py, set up the routing.

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ItemViewSet

urlpatterns = [
path('api/test', ItemViewSet.as_view()),
]

Also, don’t forget to include myapp's URLs in the project’s myproject/urls.py.

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

Migrate the Database

Screenshot 2024-10-25 130611.png

Since Django has some built-in web-app tools, it also keeps a database. While we aren't directly accessing them in this guide, we still need to run database migrations before starting the server.

python manage.py makemigrations

python manage.py migrate

Test the API

Screenshot 2024-10-25 131317.png

To start the server: python manage.py runserver

Then, to test the API, use a tool such as Postman to send a request to http://127.0.0.1:8000/api/test. You should get a response back with the text we appended in views.py.

Conclusion

You've successsfuly created a REST API using Django and Python. While this was an arbitrary example, this setup makes it quite easy to expand upon. For example, adding authentication, providing database access to a frontend server, and much more.