Mobil Mewah

Salah satu sumber Inspirasi.

Mobil Sport terbaik

Anda pasti bisa memilikinya.

Bermain dengan pesawat

Salah satu ide yang gila, Balapan di udara.

Bermain di angkasa

Apakah ini salah satu Goals dalam hidup anda? anda pasti bisa mencapainya

Showing posts with label REST. Show all posts
Showing posts with label REST. Show all posts

Tuesday, 12 September 2017

Javascript promise error handling

Javascript promise error handling
On web application, the standard will have javascript code. Especially with ajax call method and event driven application design.

One of my experience just now was with using promise in javascript. It not catch the error status code returned from the server backend, but in debug mode in the browser status returned was 401 or unauthorized. I using Marionette JS as my development framework and my backend using Chicagoboss.

So the story was that user need to login before access the API. When request coming without authorization code, it will return 401 status code. My backend API try to be Restfull. And i want my web application automatically cacth the 401 error globally and will show login form when 401 status code encountered within the app run time. So the code was like below :

            var defer = $.Deferred();
            options || (options = {});
            options.reset = true;
            defer.then(options.success, options.error);
            var response = data.fetch(_.omit(options, 'success', 'error'));
            response.done(function(){
                defer.resolveWith(response, [edonationboxes]);
            });
            response.fail(function(response){
                defer.reject(response);
            });

And i have the ajax setup when the webapp start to detect the 401 globally.

    $.ajaxSetup({
        statusCode: {
            401: function(){
                // Redirec the to the login page.
                window.location.replace('#login');
            },
            403: function() {
                // 403 -- Access denied
                window.location.replace('/#denied');
            }
        },
    });

So the problem is when i refresh page, it correctly detect the 401 and login page shown. But when application run and the request triggered within the app, by accessing a menu, it not cacthing the 401 error.

When debugging, the statusCode was 0. So google for a while, seems issue with the API backend which not returning correct headers for CORS request. So when fixed the app behave correctly. Login page show when 401 detected.

So make sure in the API response header return this : access-control-allow-origin:* 
With javascript promise, it wont behave correctly if CORS involved and not set correctly, especially in SPA web application.

Hope this helps someone, as i have debug this almost 3 hours.

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.

Twitter Delicious Facebook Digg Stumbleupon Favorites More