How to develop RESTful webservice in Django using DjangoRestFramework?

pip install djangorestframework
INSTALLED_APPS = (
...
'rest_framework',
)
from django.db import modelsclass Country(models.Model):
name = models.CharField(max_length=10)
INSTALLED_APPS = (
...
'rest_framework',
‘api’,
)
python manage.py makemigrations
python manage.py migrate
from rest_framework import serializers
from .models import *
class CountrySerializer(serializers.Serializer):
name = serializers.CharField(max_length=250)

CRUD operations:

C- Create:

  1. Function based views.
  2. Class based View.
from api.serializers import *
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .models import *
from rest_framework import status
@api_view(['POST'])
def add_county(request):
country_serializer = CountrySerializer(data=request.data)
if country_serializer.is_valid():
country_serializer.save()
return Response({"data": "Country added successfully"}, status=status.HTTP_201_CREATED)
else:
error_details = []
for key in country_serializer.errors.keys():
error_details.append({"field": key, "message": country_serializer.errors[key][0]})
data = {
"Error": {
"status": 400,
"message": "Your submitted data was not valid - please correct the below errors",
"error_details": error_details
}
}
return Response(data, status=status.HTTP_400_BAD_REQUEST)
from rest_framework import serializers
from .models import *
class CountrySerializer(serializers.Serializer):
name = serializers.CharField(max_length=250)
def create(self, validated_data):
country_obj = Country(**validated_data)
country_obj.save()
return country_obj
def update(self, instance, validated_data):
instance.name = validated_data["name"]
instance.save()
return instance
from django.conf.urls import url
from api import views
urlpatterns = [
url(r'^api/country/add/$', views.add_county),
]
country_serializer.save()
@api_view(['GET', 'POST'])
def update_county(request, id):
country_obj = Country.objects.get(id=id)
if request.method == "GET":
country_data = CountrySerializer(country_obj).data
return Response({"data": country_data}, status=status.HTTP_200_OK)
elif request.method == "DELETE":
country_obj.delete()
return Response({"data": “Country Deleted Successfully.”}, status=status.HTTP_200_OK)
else:
country_serializer = CountrySerializer(country_obj, data=request.data)
if country_serializer.is_valid():
country_serializer.save()
return Response({"data": "Country Updated successfully"}, status=status.HTTP_200_OK)
else:
error_details = []
for key in country_serializer.errors.keys():
error_details.append({"field": key, "message": country_serializer.errors[key][0]})
data = {
"Error": {
"status": 400,
"message": "Your submitted data was not valid - please correct the below errors",
"error_details": error_details
}
}
return Response(data, status=status.HTTP_400_BAD_REQUEST)
urlpatterns = [
url(r'^api/country/add/$', views.add_county),
url(r'^api/country/(?P<id>[^/]*)/$', views.update_county),
]
CountrySerializer(country_obj).data
country_data = CountrySerializer(country_queryset, many=True).data
[{‘name’:’India’, ’name’:’Japan’,....}]

The article was originally published at MicroPyramid blog.

--

--

--

Python, Django, Android and IOS, reactjs, react-native, AWS, Salesforce consulting & development company

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Remove Nth Node From End of List — Day 107(Python)

Use UPS API to Get Rates, Generate Labels, and Track Shipments

Flutter: Implement network-aware in your Flutter app

Customizing Bash Command Prompt?

Animation of 2D sprites in Unity is fun :)

Naming a Protocol in Swift

Framework 1: Health Pick Ups

Pros and cons of using Flutter framework

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
MicroPyramid

MicroPyramid

Python, Django, Android and IOS, reactjs, react-native, AWS, Salesforce consulting & development company

More from Medium

Virtual environment set up for Django Application

How to create desktop notifications in Django?

A Simple CRUD Application with Django

Django website night mode: The cleanest and easiest way.