Django makes it easy to create and manage RESTful APIs, especially when combined with the Django REST Framework (DRF). RESTful APIs allow different parts of an application
to communicate over HTTP, making Django a great choice for full-stack development.
Steps to create a RESTful API in Django:
1. Install Django REST Framework (DRF):
pip install djangorestframework
2. Add DRF to your Django project:
# In settings.py
INSTALLED_APPS = [
'rest_framework',
...
]
3. Create a Django model:
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
description = models.TextField()
def __str__(self):
return self.name
4. Create a Serializer for the model:
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
5. Create API Views:
from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
6. Define URL routes for the API:
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ProductViewSet
router = DefaultRouter()
router.register(r'products', ProductViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
Now you have a fully functional RESTful API to handle product data, which can be integrated into a full-stack application using Django for the backend and a front-end
framework like React or Angular.