Developing a REST API with Django REST Framework

This comprehensive guide takes you through the process of building a REST API with the Django REST Framework (DRF) from scratch. Step-by-step instructions and output examples are provided to help you understand the key concepts

image description

Here's an example of building a REST API with the Django REST Framework (DRF) from scratch, step by step, with output:

This comprehensive guide takes you through the process of building a REST API with the Django REST Framework (DRF) from scratch. Step-by-step instructions and output examples are provided to help you understand the key concepts and how to implement them. Whether you are a beginner or an experienced developer, this guide will help you get up to speed with developing REST APIs using DRF and Django.

  1. Prerequisites:

  2. Installation:

    • Open your terminal/command prompt and run the following command to install DRF:
pip install djangorestframework
  1. Creating a Django Project:
    • Run the following command in your terminal/command prompt to create a Django project:
django-admin startproject myproject
  1. Creating a Django App:
    • Navigate to the project directory using the following command:
cd myproject

Run the following command to create a Django app:

python manage.py startapp myapp
  1. Setting up DRF:
    • Open the myproject/settings.py file and add 'rest_framework' to the INSTALLED_APPS list.
    • Add the following code to the settings.py file:
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
    ],
}
  1. Creating Models:
    • Open the myapp/models.py file and define your model. For example:
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    description = models.TextField()
    published_date = models.DateField()

    def __str__(self):
        return self.title

Run the following command to apply the changes to the database:

python manage.py makemigrations

Finally, run the following command to apply the changes to the database:

python manage.py migrate
  1. Serializers:
    • Create a myapp/serializers.py file and define your serializer. For example:
from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'title', 'author', 'description', 'published_date')
  1. Views:
    • Create a myapp/views.py file and define your views. For example:
from rest_framework import generics
from .models import Book
from .serializers import BookSerializer

class BookList(generics.ListCreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

class BookDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
  1. URLs:
    • Open the `myapp/urls.py` file and define your URLs. For example:
from django.urls import path
from .views import BookList, BookDetail

urlpatterns = [
path('books/', BookList.as_view(), name='book-list'),
path('books/int:pk/', BookDetail.as_view(), name='book-detail'),
]
  1. URLs:
    • Add the following code to the `myproject/urls.py` file:
from django.urls import path, include

urlpatterns = [
path('api/', include('myapp.urls')),
]
  1. Testing the API::
    • Run the following command to start the development server:
python manage.py runserver
  1. Open your web browser and navigate to `http://localhost:8000/api/books/` to see the list of books.
  2. To see the details of a specific book, navigate to `http://localhost:8000/api/books/<book_id>/`, where `<book_id>` is the ID of the book.

This is a basic example of building a REST API with the Django REST Framework. You can further customize it as per your requirements.

Reference doc:

The official documentation of Django REST Framework (DRF) can be found at the following link: https://www.django-rest-framework.org/

You can also refer to the DRF tutorials and guides section for more in-depth information and reading materials: https://www.django-rest-framework.org/tutorials/

Conclusion :

In conclusion, developing a REST API with the Django REST Framework is a manageable task that can be done with basic knowledge of Django and DRF. DRF provides clear documentation, tutorials, and tools that make it possible for developers of different skill levels to build robust and scalable APIs. This guide provides a starting point for building REST APIs using DRF and Django, and should be helpful for personal projects or client work.

 

DigitalOcean Referral Badge

DigitalOcean Sign Up : If you don't have a DigitalOcean account yet, you can sign up using the link below and receive $200 credit for 60 days to get started: Start your free trial with a $200 credit for 60 days link below: Get $200 free credit on DigitalOcean ( Note: This is a referral link, meaning both you and I will get credit.)


Latest From PyDjangoBoy

👩💻🔍 Explore Python, Django, Django-Rest, PySpark, web 🌐 & big data 📊. Enjoy coding! 🚀📚