REpresentational State Transfer + Application Programming Interface
REST API allows different applications (like mobile apps, frontend, backend) to talk to each other over the internet using HTTP methods (like GET, POST, PUT, DELETE).
What is REST API in Django?
In Django, you can create REST APIs using the library called Django REST Framework (DRF).
With REST API in Django, you can:
Send data to the backend (POST)
Get data from the backend (GET)
Update existing data (PUT/PATCH)
Delete data (DELETE)
pip install djangorestframework
INSTALLED_APPS = [
...
'rest_framework',
]
| Method | Endpoint | Purpose | Example |
| ------ | ------------------------- | -------------------- | ----------- |
| GET | `/api/students/` | Get all students | List view |
| GET | `/api/students/1/` | Get 1 student (id=1) | Detail view |
| POST | `/api/students/create/` | Create new student | Add |
| PUT | `/api/students/update/1/` | Update student id=1 | Edit |
| DELETE | `/api/students/delete/1/` | Delete student id=1 | Remove |
{
"name": "Raj",
"age": 22,
"city": "Ahmedabad"
}
✅ What is a Serializer?
A Serializer in DRF is used to convert complex data types such as Django models into JSON format (for API responses), and vice versa (for handling incoming data).
What Serializers Do:
| Direction | Purpose |
| ---------------- | ---------------------------------------------------- |
| **Model → JSON** | For sending data to frontend/API clients |
| **JSON → Model** | For receiving data from clients (like create/update) |
Why Use Serializers?
To convert Django models into JSON
To convert incoming JSON into Django models
✅ What are HTTP Status Codes?
HTTP status codes tell the client (like browser or Postman) whether a request was successful, failed, or had an error.
| Code | Meaning | Used When... |
| ---- | --------------------- | ------------------------------------------ |
| 200 | OK | Everything worked fine (GET, PUT) |
| 201 | Created | New object was successfully created (POST) |
| 204 | No Content | Successfully deleted (DELETE) |
| 400 | Bad Request | Invalid data sent by client |
| 401 | Unauthorized | Not logged in or no permission |
| 403 | Forbidden | You’re not allowed to access this |
| 404 | Not Found | Data with given ID doesn't exist |
| 500 | Internal Server Error | Something wrong on server side |
name
id'
salary
{
"name":"ramesh",
"id":101,
"salary":4400,
}
📁 Project Structure
myproject/
├── main/
│ ├── models.py
│ ├── serializers.py
│ ├── views.py
│ └── urls.py
├── myproject/
│ └── settings.py
│ └── urls.py
🔧 1. Install & Setup
pip install django djangorestframework
django-admin startproject myproject
cd myproject
python manage.py startapp main
🔧 2. settings.py (Enable DRF + App)
# myproject/settings.py
INSTALLED_APPS = [
...
'rest_framework',
'main',
]
✅ 3. models.py
# main/models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
city = models.CharField(max_length=100)
def __str__(self):
return self.name
python manage.py makemigrations
python manage.py migrate
✅ 4. serializers.py
# main/serializers.py
from rest_framework import serializers
from .models import Student
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'
✅ 5. views.py
# main/views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import Student
from .serializers import StudentSerializer
# ✅ GET All Students
@api_view(['GET'])
def get_all_students(request):
students = Student.objects.all()
serializer = StudentSerializer(students, many=True)
return Response(serializer.data)
# ✅ GET One Student
@api_view(['GET'])
def get_single_student(request, pk):
try:
student = Student.objects.get(pk=pk)
except Student.DoesNotExist:
return Response({'error': 'Student not found'}, status=404)
serializer = StudentSerializer(student)
return Response(serializer.data)
# ✅ POST (Create Student)
@api_view(['POST'])
def create_student(request):
serializer = StudentSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)
# ✅ PUT (Update Student)
@api_view(['PUT'])
def update_student(request, pk):
try:
student = Student.objects.get(pk=pk)
except Student.DoesNotExist:
return Response({'error': 'Student not found'}, status=404)
serializer = StudentSerializer(student, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=400)
# ✅ DELETE Student
@api_view(['DELETE'])
def delete_student(request, pk):
try:
student = Student.objects.get(pk=pk)
except Student.DoesNotExist:
return Response({'error': 'Student not found'}, status=404)
student.delete()
return Response({'message': 'Student deleted successfully'}, status=204)
✅ 6. main/urls.py
# main/urls.py
from django.urls import path
from .views import (
get_all_students,
get_single_student,
create_student,
update_student,
delete_student
)
urlpatterns = [
path('api/students/', get_all_students), # GET All
path('api/students/<int:pk>/', get_single_student), # GET One
path('api/students/create/', create_student), # POST
path('api/students/update/<int:pk>/', update_student), # PUT
path('api/students/delete/<int:pk>/', delete_student), # DELETE
]
✅ 7. myproject/urls.py
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
]
Comments
Post a Comment