DEV Community

Cover image for Basic CRUD API using Django and Django REST Framework (DRF) || Simple API for managing a list of books.
mayowa-kalejaiye
mayowa-kalejaiye

Posted on • Updated on

Basic CRUD API using Django and Django REST Framework (DRF) || Simple API for managing a list of books.

It's day #2 of #100daysofMiva guys🎊.

GitHub logo mayowa-kalejaiye / BookMania-API

A simple API(It's still going to be upgraded) for managing list of books. Subscribe and see where this grows to

BookMania API

100 Days of Miva - API and Front-end Projects

#100daysofMiva Banner

Welcome to my repository for the #100daysofMiva challenge! This repository contains a collection of 100 simple API projects developed over 100 days. The challenge is all about consistency, learning, and building resilience through daily coding.

About the Challenge

The #100daysofMiva challenge is designed to help developers, especially students of Miva Open University, develop a strong work ethic by committing to coding every day. The goal is to spend at least one hour each day working on a small project, pushing the boundaries of our skills, and documenting our progress.

Repository Structure

This repository is organized into three main sections, each corresponding to a different programming language:

/100daysofMiva
β”œβ”€β”€ README.md
β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ banner.jpg
β”‚   └── (other assets)
└── Projects/
    β”œβ”€β”€ Day 1 | hello world API/
    β”‚   β”œβ”€β”€ php/
    β”‚   β”œβ”€β”€ nodejs/
    β”‚   β”œβ”€β”€ python/
    β”‚   └── README.md...
  • …

You can check out the repository for further information...
note:_Some parts have been upgraded and still under production...changes are due to happen as time goes....
_
Alright let's begin, Shall we ?

CRUD API testing

CRUD API testing

Today I decided to work on a mini-project following the CRUD API pattern. This API currently allows me to::

  • Create: Add new resources,
  • Read: Retrieve or view existing resources,
  • Update: Modify or update existing resources, and

  • Delete:Remove resources

For example, in a CRUD API for a blog, you would have endpoints for creating a new post, retrieving posts, updating a post, and deleting a post. Each operation corresponds to a different HTTP method.:

  • POST for Create
  • GET for Read
  • PUT or PATCH for Update
  • DELETE for Delete

These APIs are fundamental in web development, allowing for the manipulation and retrieval of data.

I will walk us through how I have created a straightforward CRUD API using Django and Django REST Framework (DRF) to manage a list of books. Let's get wokeπŸ’ͺ.

Step-by-Step Guide

1. Set Up Your Django Project

First, make sure you have Django and Django REST Framework installed. You can install them using pip if you haven't already:

pip install django djangorestframework
Enter fullscreen mode Exit fullscreen mode

Create a new Django project and a new app within it:

django-admin startproject myproject
cd myproject
python manage.py startapp books
Enter fullscreen mode Exit fullscreen mode
  • startproject: This command creates a new Django project. A project is a collection of settings for an instance of Django, including database configuration, Django-specific options, and application-specific settings.
  • startapp: This creates a new app within the project. Apps are components of your project that handle specific functionality (e.g., user management).

2. Configure Your Django Project

Add your new app and DRF to your INSTALLED_APPS in myproject/settings.py:

INSTALLED_APPS = [
   ...
   'rest_framework',
   'books',
]
Enter fullscreen mode Exit fullscreen mode
  1. Define the Model In books/models.py, define a Book model: this is where you design how you want to input data, it depends on what exactly you want to do
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_date = models.DateField()
    isbn = models.CharField(max_length=13, unique=True)
    pages = models.IntegerField()
    cover = models.URLField(blank=True)
    language = models.CharField(max_length=20)

    def __str__(self):
        return self.title

Enter fullscreen mode Exit fullscreen mode

Then you run migrations to create the database schema:

python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Always do this once your books/models.py has been updated, iterated or refurbished....so that it will be consistent

Moving on...😁

4. Create a Serializer

Create a serializer for your model in books/serializers.py:
By using serializers, you ensure that the data your API sends and receives is well-organized, validated, and easily understandable, making it a critical part of any Django REST API.

from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'
Enter fullscreen mode Exit fullscreen mode

5. Create Views

Define views for your API in books/views.py using DRF’s viewsets: By understanding views, you gain control over how data flows through the application, making it a critical aspect of building APIs with Django REST Framework.

from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
Enter fullscreen mode Exit fullscreen mode

Now we move to our routing...πŸ₯Ή Kudos to you for coming this far😁...

6. Configure URLs

Set up URLs to route API requests. First, create a file books/urls.py: URLs in Django map the paths of incoming HTTP requests to the appropriate view functions or classes. In Django REST Framework (DRF), URLs are used to define how different endpoints of your API are accessed.

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

router = DefaultRouter()
router.register(r'books', BookViewSet)

urlpatterns = [
    path('', include(router.urls)),
]
Enter fullscreen mode Exit fullscreen mode

What is path()?
In Django, path() is a function used to define a URL pattern and link it to a specific view.
Think of it as a map that directs incoming web requests to the correct view, which then processes the request and returns a response.

What is include()?
The include() function allows you to include other URL configurations. In this example, it includes the URLs automatically generated by a DRF router.

Then, include these URLs in the projects's myproject/urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('books.urls')),
]
Enter fullscreen mode Exit fullscreen mode

Understanding URLs might be really tricky so...
I WILL EXPLAIN EVERYTHING ABOUT URLs IN MY NEXT POST

Digging through to the next step....😀

7. Run the Development Server

Start the Django development server:

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Your API should be accessible at http://localhost:8000/api/books/.

The fun step-8. Test the API

You can test the API using tools like Postman or curl, or visit the URL in your browser to use Django REST Framework's built-in web interface.

Now what is coding without bugs huh?πŸ˜‰Some of us might encounter errors on the way but I've got you covered😁///
Here are some common errors and their solutions specifically for the CRUD API project you just worked on:

Error: ModuleNotFoundError: No module named 'your_app'
Solution: Ensure that your app is listed in INSTALLED_APPS in settings.py, and check for any typos in your urls.py or views.py.

Error: ImportError: Could not import 'rest_framework'
Solution: Install Django REST framework using pip install djangorestframework, and ensure it's added to INSTALLED_APPS.

Error: AssertionError: 'YourViewSet' should either include a serializer_class attribute, or override the get_serializer_class() method.
Solution: In your views.py, make sure your ViewSet has a serializer_class attribute that points to the correct serializer.

Error: IntegrityError: UNIQUE constraint failed
Solution: This occurs when trying to insert duplicate values in a field that requires unique entries. Make sure the data you are saving does not violate this constraint.

Error: ProgrammingError: relation "your_model" does not exist
Solution: Run python manage.py makemigrations and python manage.py migrate to ensure the database schema is up to date.

IF YOU HAVE ANY QUESTION, FEEL OBLIGED TO PUT THEM IN THE COMMENT SECTION...πŸ˜‰

Happy Coding!
Happy Growing!

Top comments (4)

Collapse
 
tobidelly profile image
TD!

Well done πŸ‘πŸ½

Collapse
 
mayowakalejaiye profile image
mayowa-kalejaiye

Thank you πŸ™

Collapse
 
marvellye profile image
Ezekiel Marvellous

This is amazing project ✨

Collapse
 
mayowakalejaiye profile image
mayowa-kalejaiye

Thank youπŸš€