Django Rest Framework

 Django rest framework aka is very good framework form making API.



we can simply get the json format by using JsonResponse


from django.http import JsonResponse

return JsonResponse({key:value})



To install djangorest framework

simply do

pip install djangorestframework


json ----> python format is deserializaion

python format ====> json is serialization

from rest_framework.parsers import JSONParser

we can use JSONParser to parse json


serializer is used to validate data


from rest_framework.response import Response

we can use Response instead of JsonResponse


serializer=SerializerClass(queryset,many=True)



in deserialization
        serializer = Add2NumSerializer(data=data)
        if serializer.is_valid():
            n1 = serializer.validated_data['number1']
            n2 = serializer.validated_data['number2']
            result = n1+n2
            return Response({
                "result": result
            })
        print(serializer.errors)
        return Response({
            serializer.errors
        })


instead of above code we can simply do

        serializer = Add2NumSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            n1 = serializer.validated_data['number1']
            n2 = serializer.validated_data['number2']
            result = n1+n2
            return Response({
                "result": result
            })
    




Comments