Thursday 9 June 2016

Rest API with Django REST framework

Rest API with Django REST framework
When working with REST Api in your own application, you want to create a REST api which is follow the web standard of REST. In python , especially Django Worl, you can use Django REST framework. It support the REST Method , GET, POST, PUT, DELETE and handle it for you in the back ground.

So with this blog post, i want to have a post about my experience on working with Django REST framework. I never use it until my requirement for application goes to Mobile app, which surely the front end can be build using any hybrid method using javascript library/frameworks available, and in the back end, Python + Django still my super hero.

OK lets start, the Views in Django will be the same with Views in Django REST framework. And also the model will still be the same. We will reuse the model we already have. So the flow of creating a REST api in Django REST framework are :

1. Create Model
2. Create Serializer for the model
3. Create view for the model
4. Assign to the url.py of django

With this you will get the API browseable UI with only the above effort for you to test the API.

Step1. The models.py

from django.db import models

class Sms(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    message = models.CharField(max_length=100, blank=True, default='')
    phone = models.TextField()
   
    class Meta:
        ordering = ('created',)


Step 2. the serializers.py

from rest_framework import serializers
from sms.models import Sms


class SmsSerializer(serializers.Serializer):

      model = Sms
        fields = ('id','created','message','phone')


Step 3. The view.py

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from sms.models import Sms
from sms.serializers import SmsSerializer


@api_view(['GET', 'POST'])
def sms_list(request):
    """
    List all sms, or create a new sms
    """
    if request.method == 'GET':
        sms = Sms.objects.all()
        serializer = SmsSerializer(sms, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = SmsSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
def sms_detail(request, pk):
    """
    Retrieve, update or delete a sms instance.
    """
    try:
        sms = Sms.objects.get(pk=pk)
    except Sms.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = SmsSerializer(sms)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = SmsSerializer(sms, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        sms.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)



step 4. The url.py :

from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from sms import views

urlpatterns = [
    url(r'^sms/$', views.sms_list),
    url(r'^sms/(?P[0-9]+)$', views.sms_detail),
]

urlpatterns = format_suffix_patterns(urlpatterns)

So the above step is how to create an api with your way, and full control on the views method you do before return the data to the rest api users.

There are another way to reduce your typing with Django REST framework, and i will post in on another blogpost.

So here it is, Django REST frameork.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More