LearnCodeGuide
5 min readSep 6, 2023

How to Create a REST API with Django Rest Framework for beginner (Full Tutorial)

How to Create a REST API with Django Rest Framework for beginner full tutorial

How to Create a basic API using Django Rest Framework

Create a REST API With Django REST Framework

How to create a REST API with Django REST framework

Why Django Rest Framework:

Django Rest Framework (DRF) is a toolkit for architecture Web APIs with Django, authoritative it easier to create, test, and certificate APIs. It simplifies accepted tasks like abstracts serialization, authentication, and permissions, acceptance developers to actualize able APIs efficiently. The DRF affidavit is absolute and serves as a admired ability for developers.

follow my telegram channel

https://t.me/learncodeguide

Project Structure

djangorestframework structure

First environment activate *

Environment Setup

Virtual Environment:

It’s best convenance to actualize a basic ambiance to abstract your project’s dependencies. Use `venv` or `virtualenv` to actualize one:

Create a Virtual Environment: (windows)

Create a virtual environment using the built-in venv module:

Open a Command Prompt and navigate to your project directory.

python -m venv venv_name

Structure

python Environment setup

Activate the virtual environment:

venv_name\Scripts\activate

Create a Virtual Environment:(macOS)

Open Terminal and navigate to your project directory.

Create a virtual environment using the built-in venv module:

python3 -m venv venv_name

Activate the virtual environment:

source venv_name/bin/activate

Notes :conform environment activate next go it *

Django Installation:

Django Install in terminal:

pip install django

Django Rest Framework Installation

Install DRF application pip:

pip install djangorestframework

Database Setup:

Configure your database settings in projectname/settings.py. You can use the absence SQLite database for development.

Create a Django Project and App

Project Creation: Create a new Django project:

django-admin startproject projectname

App Creation: Create a Django app within the project:

cd projectname

python manage.py startapp myapp

Configure Django Settings ( Importent)

Open `projectname/settings.py` and add `’rest_framework’` to the `INSTALLED_APPS` list:

INSTALLED_APPS = [
# …
'rest_framework', # add this
'myapp', # add this
]

Create a Model

In your app’s `models.py`, ascertain your model. For example, a `Task` model:

from django.db import models

class Task(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
completed = models.BooleanField(default=False)

def __str__(self):
return self.title

Creating Serializers:

In your app’s serializers.py file, create serializers for your models. These serializers determine how data should be serialized.

For example, for the Task model:

from rest_framework import serializers
from .models import Task

class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = '__all__'

Creating View :

Ascertain angle in `views.py` to handle CRUD operations application DRF’s all-encompassing views:

Create a Task first

from rest_framework import generics
from .models import Task
from .serializers import TaskSerializer
class TaskListCreateView(generics.ListCreateAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer

Get single and all task GET method

get method single or multiple task get method

from rest_framework import generics
from .models import Task
from .serializers import TaskSerializer
class TaskDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer

class AllTasksListView(generics.ListAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer

Edit in task Update method

task editing or updating method

from rest_framework import generics
from .models import Task
from .serializers import TaskSerializer
class TaskUpdateView(generics.RetrieveUpdateAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer
partial = True

Delete in Task DETELE method:

task delete method

from rest_framework import generics
from rest_framework import status
from rest_framework.response import Response
from .models import Task
from .serializers import TaskSerializer

class TaskDeleteView(generics.DestroyAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer

def destroy(self, request, *args, **kwargs):
instance = self.get_object()
instance.delete()
return Response(print("delete task"))

Finally views.py

overall view page view.py file is

from rest_framework import generics
from rest_framework import status
from rest_framework.response import Response
from .models import Task
from .serializers import TaskSerializer

class TaskListCreateView(generics.ListCreateAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer

class TaskDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer

class AllTasksListView(generics.ListAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer


class TaskUpdateView(generics.RetrieveUpdateAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer
partial = True



class TaskDeleteView(generics.DestroyAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer

def destroy(self, request, *args, **kwargs):
instance = self.get_object()
instance.delete()
return Response(print("delete task"))

Create in app URLs:

Create your app’s urls.py to include the URL pattern for your views:


from django.urls import path
from .views import TaskListCreateView, TaskDetailView,AllTasksListView,TaskDeleteView,TaskUpdateView

urlpatterns = [
path('tasks/', TaskListCreateView.as_view(), name='task-list-create'),
path('tasks/<int:pk>/', TaskDetailView.as_view(), name='task-detail'),
path('tasks/all/', AllTasksListView.as_view(), name='all-tasks-list'),
path('tasks/delete/<int:pk>/', TaskDeleteView.as_view(), name='task-delete'),
path('tasks/update/<int:pk>/', TaskUpdateView.as_view(), name='task-update'),

]

Project Urls:

Add in app url in project

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

urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('myapp.urls')), # Include your app's URLs
]

Migrations and Database Setup

Run migrations to actualize the database tables for your model:

python manage.py makemigrations

python manage.py migrate

Run the Development Server

- Start the development server:

python manage.py runserver

result :

System check identified no issues (0 silenced).

September 03, 2023–07:09:00

Django version 4.2.4, using settings ‘projectname.settings’

Starting development server at http://127.0.0.1:8000/

Quit the server with CTRL-BREAK.

Your API is now working at `http://localhost:8000/`.

API Endpoints

- Document the accessible API endpoints and their functionalities:

- `POST /api/tasks/` — Create a new task.

- `GET /api/tasks/{task_id}/` — Retrieve a specific task.

- `GET /api/tasks/all/` — List all tasks.

- `PUT /api/tasks/{task_id}/` — Update a specific task.

- `DELETE /api/tasks/{task_id}/` — Delete a specific task.

Testing

- Accommodate advice on how to analysis your API endpoints application accoutrement like Postman or cURL.

Postman Run Example

Post method :

Create a task :

url : http://localhost:8000/api/tasks/

Open postman open body select raw select in Json format

{
"title": "learncodeguide",
"description": "any doubt comment me"
}

GET SINGLE TASK :

url : http://localhost:8000/api/tasks/<id>/

GET ALL TASK

url : http://localhost:8000/api/tasks/all/

UPDATE TASK:

url : http://localhost:8000/api/tasks/update/<ID>/

Open postman next.open Body select in raw next select in json format

{
"title": "LEARNCODEGUIDE",
"description": "Any Doubt Comment Me"
}

DELETE TASK

URL : http://localhost:8000/api/tasks/delete/<ID>/

Conclusion:

- Summarize the key credibility of your project, its purpose, and any added advice that ability be helpful.

follow my telegram channel

https://t.me/learncodeguide

More detail get commet it and say What you wand say me in comment

LearnCodeGuide

I am Software Developer .i am give in all programming language code , guide and clarification