How to make fail-safe APIs in Django

While making APIs we must ensure that whatever happens, we must give proper response to the called API. I will be sharing my approach to make fail-safe APIs in Django. By fail-safe, I mean that no matter what, if an API is called it must be responded with a proper JSON or XML.

Two Approaches

If you have been coding for a bit time now then you probably must know about error handling. Or more specifically try, catch and except block. We generally use it to encounter the cases that may cause some errors. Let us consider a very simple example. A program that divides two given numbers. Now imagine what if the second number is zero. It is obvious that we can not divide any number by zero. So it is an exception while dividing two numbers.

Errors and Exceptions

There is a big difference between an error and an exception.

An error is something like, something severe enough has gone wrong that the most applications should crash rather than try to handle the problem.
An exception too shows that something wrong has occurred but the application can recover from it. In more general words the cause of exceptions are the known cases which may cause errors. You may consider it as the knowledge of the fact that diving a number by zero will lead to an error. So before dividing two numbers, we check whether it is not the case of divide by zero. And if it is then we throw an exception as cannot divide by zero.

First method

The first method to make an API fail safe is by putting a try-except block in your views. It is something like you bet on try block if it fails due to any reason then the except block will be executed. So here a simple code snippet which reflects the same.

def some_view(request):
response = {}
try:
response['success'] = True
response['message'] = 'Some Message'
# do something
except(Exception as e):
response['success'] = False
response['message'] = 'Sorry an error occured'
# You may create a log or call a webhook or can do anything
return JsonResponse(response)

It looks great but there are many API’s and you will have to write views with repeating the same thing. And Django provides an amazing thing, it is called a decorator.

Decorators

Decorators are something that holds that particular view. It is like calling a function that will be calling that view or it will be holding that view in itself. Django provides many decorators that can be applied to views. You can check the official Django documentation about decorators. So I have made an decorator which makes an API fail-safe i.e. no matter what the API call will always result in a proper JSON/XML response. A decorator looks like

def decorator_name(function):
def wrap(request, *args, **kwargs):
return function(request, *args, **kwargs)
wrap.__doc__ = function.__doc
wrap.__name__ = function.__name__
return wrap

You may understand it something like return function(request, *args, **kwargs) actually executes the view. So I did a little tweak and put return function(…) inside try block. And thus wherever we will be using the decorator that view will automatically be inside try except block. And hence just by simply using a decorator we can do the same thing without repeating ourselves. And do not forget that Django has a philosophy that don’t repeat yourself.

def controller_api(function):
def wrap(request, *args, **kwargs):
try:
return function(request, *args, **kwargs)
except:
response = {}
response['success'] = False
response['message'] = "Sorry an error occured please try again"
return JsonResponse(response)
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap

So the above code snippet is the final decorator. Create a file named decorators.py in the root of the project directory and it can be imported in the views.py as from decorators import controller_api . There are many things in web development like scaling, load balancing etc. So the above method may not work if you have a different problem. More precisely if your server is able to handle traffic and bear the load than with the above method you may ensure that your APIs are never going to fail.

I am a full stack developer. Ping me at kuldeep@techflexa.com for any inquiry related to app and web development.

Follow me on LinkedIn, GitHub. I often write about entrepreneurship and startups on my blog HappyChases at my free time. You may subscribe there too.

Hope you learned something. :-)

Like what you read? Give Kuldeep Pisda a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.