03 Aug 2024 by Ijeoma Jahsway

Category: Web Development

Frameworks: Django, Django REST Framework

Read Time: 10 Minutes


How to Build a REST API with Django and Django REST Framework

How to Build a REST API with Django and Django REST Framework

Picture this: You're at a fancy restaurant, and you’re the hungry customer. The kitchen is where the magic happens, but you can't go back there yourself. Instead, you tell the waiter your order, and they deliver it to the kitchen. After a while, the waiter returns with your delicious meal. In the world of tech, an API (Application Programming Interface) is just like that waiter! It takes your requests, tells the system what you need, and brings back the goodies.

Although you can build your own API directly from a programming language of your choice, namely;

1. Python

2. JavaScript (Node.js)

3. Java

4. C#

5. PHP

There are various frameworks built specifically for creating robust APIs, here are a few of them

 

1. Django REST Framework: Django in a superhero cape, ready to build robust APIs.

2. Express.js: A quick and nimble node.js framework, like a speedy waiter on roller skates.

3. Flask: A lightweight and flexible Python framework, like a friendly neighborhood diner.

4. Spring Boot: Java-powered and reliable, like a top-notch butler.

In this article, we'll walk through the steps of creating a simple REST API using Django and Django REST Framework (DRF). We'll create a basic API for a to-do list application. By the end of this guide, you'll understand how to set up a Django project, configure Django REST Framework, and create CRUD operations for a to-do list. Let's get started!

Prerequisites

Before we start, make sure you have the following installed:

You can install Django and DRF from your terminal using pip:

pip install django
pip install djangorestframework

Step 1: Set Up the Django Project

First, let's create a new Django project. Open your terminal and run the following commands:

django-admin startproject todo_project

# Change directory into the new project
cd todo_project

Next, create a new app called todos:

python manage.py startapp todos

Add the new app and Django REST Framework to your INSTALLED_APPS in todo_project/settings.py:

# todo_project/settings.py

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

Step 2: Create the To-Do Model

In the todos app, create a simple model for the to-do items. Open todos/models.py and define the model:

# todos/models.py

from django.db import models

class Todo(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title

After defining the model, create and apply the migrations:

python manage.py makemigrations
python manage.py migrate

Step 3: Create the Serializers

Serializers in Django REST Framework convert complex data types (like Django models) into JSON and vice versa.

Imagine you're writing a letter to a friend who speaks another language. You need a translator to convert your message so they can understand it. Here, serializers are those translators! They take complex data from your application (like Python objects and in this case, your Django models) and convert it into a format that can be easily sent over the internet (like JSON). And when data comes back, serializers translate it back into a form your app can understand.

Now let's create a new file todos/serializers.py and define a serializer for the Todo model:

# todos/serializers.py

from rest_framework import serializers
from .models import Todo

class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Todo
        fields = '__all__'

Step 4: Create the Views

Next, create views to handle the API endpoints. Open todos/views.py and define the views using Django REST Framework's generic views:

# todos/views.py

from rest_framework import generics
from .models import Todo
from .serializers import TodoSerializer

class TodoListCreate(generics.ListCreateAPIView):
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer

class TodoRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer

Step 5: Define the URLs

Now, let's define the URLs for the API endpoints. Create a new file todos/urls.py and add the following code:

# todos/urls.py

from django.urls import path
from .views import TodoListCreate, TodoRetrieveUpdateDestroy

urlpatterns = [
    path('todos/', TodoListCreate.as_view(), name='todo-list-create'),
    path('todos/<int:pk>/', TodoRetrieveUpdateDestroy.as_view(), name='todo-retrieve-update-destroy'),
]

Include the todos URLs in the main project's URL configuration. Open todo_project/urls.py and modify it as follows:

# todo_project/urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('todos.urls')),
]

Step 6: Test the API

With everything set up, you can now run the Django development server and test the API:

python manage.py runserver

You can use tools like Postman or curl to interact with the API endpoints. Here are some examples using curl:

  1. Create a new to-do item:

curl -X POST -H "Content-Type: application/json" -d '{"title": "Buy groceries", "description": "Milk, Eggs, Bread"}' http://127.0.0.1:8000/api/todos/

        2. List all to-do items:

curl http://127.0.0.1:8000/api/todos/

        3. Retrieve a specific to-do item:

curl http://127.0.0.1:8000/api/todos/1/

        4. Update a to-do item:

curl -X PUT -H "Content-Type: application/json" -d '{"title": "Buy groceries", "description": "Milk, Eggs, Bread, Cheese", "completed": true}' http://127.0.0.1:8000/api/todos/1/

        5. Delete a to-do item:

curl -X DELETE http://127.0.0.1:8000/api/todos/1/

 

Conclusion

In this guide, we've covered some interesting things like how to set up a Django project, how to create a model, and how touse Django REST Framework to build a REST API. This basic setup can be extended and customized to fit more complex requirements, such as user authentication, permissions, and more sophisticated data handling.

Subscribe to our newsletter to get notified when new articles are uploaded so you don't miss out on the next steps for creating a more robust API. 

Feel free to engage in the comments and share you thoughts, opinion and any questions you might have concerning the topic. Thank you.

 

Join Us on Telegram!

Join our Telegram group to get exclusive content and be the first to know when new blog posts go live! 🎉

Comments

No comments...

Leave a Comment

Author
Ijeoma Jahsway
Ijeoma Jahsway @admin

#Python #API Development #Django Tutorial #REST API #Django #Web Development #Django REST Framework

Delta State, Nigeria

Related Articles

See More

For you

See More