To integrate a new REST API in our bulletin_board app, execute the following steps:
- Add configurations for the Django REST Framework to the settings as shown here:
# settings.py or conf/base.py REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions."
"DjangoModelPermissionsOrAnonReadOnly"
],
"DEFAULT_PAGINATION_CLASS":
"rest_framework.pagination.LimitOffsetPagination",
"PAGE_SIZE": 100,
}
- In the bulletin_board app, create the serializers.py file with the following content:
# bulletin_board/serializers.py
from rest_framework import serializers
from .models import Category, Bulletin
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ["id", "title"]
class BulletinSerializer(serializers.ModelSerializer):
class Meta:
model = Bulletin
fields = ["id", "bulletin_type", "title",
"description", "contact_person", "phone",
"email", "image", "category"]
category = CategorySerializer()
def create(self, validated_data):
category_data = validated_data.pop('category')
category, created = Category.objects.get_or_create(
title=category_data['title'])
bulletin = Bulletin.objects.create(category=category,
**validated_data)
return bulletin
def update(self, instance, validated_data):
category_data = validated_data.pop('category')
category, created = Category.objects.get_or_create(
title=category_data['title'])
for fname, fvalue in validated_data.items():
setattr(instance, fname, fvalue)
instance.category = category
instance.save()
return instance
- Add two new class-based views to the views.py file in the bulletin_board app:
# bulletin_board/views.py
from rest_framework import generics
from .models import Bulletin
from .serializers import BulletinSerializer
# ...
class RESTBulletinList(generics.ListCreateAPIView):
queryset = Bulletin.objects.all()
serializer_class = BulletinSerializer
class RESTBulletinDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Bulletin.objects.all()
serializer_class = BulletinSerializer
- Finally, plug in the new views to the project URL configuration:
# project/urls.py from django.urls import include, path
from bulletin_board.views import (RESTBulletinList,
RESTBulletinDetail) urlpatterns = [ # ...
path("api-auth/",
include("rest_framework.urls",
namespace="rest_framework")),
path("rest-api/bulletin-board/",
RESTBulletinList.as_view(),
name="rest_bulletin_list"),
path("rest-api/bulletin-board/<int:pk>",
RESTBulletinDetail.as_view(),
name="rest_bulletin_detail"), ]