Created
February 16, 2017 17:51
-
-
Save emiel/1cbc4af357e89792754f93f64ea6a969 to your computer and use it in GitHub Desktop.
Simple Django REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import HttpResponse | |
class ApiResponse(HttpResponse): | |
def __init__(data, **kwargs): | |
kwargs.setdefault("content_type", "application/json") | |
content = json.dumps(data) | |
super(ApiResponse, self).__init__(content=data, **kwargs) | |
class ApiException(Exception): | |
def __init__(self, message, status=400): | |
self.message = message | |
self.status = status | |
def to_response(self): | |
return ApiResponse({"message": self.message}, status=self.status) | |
class ApiMiddleWare(object): | |
def process_exception(request, exception): | |
if instanceof(ApiException, exception): | |
return exception.to_response() | |
else: | |
return None | |
def add_numbers(request): | |
a = request.GET.get("a", None) | |
b = request.GET.get("b", None) | |
result = {"sum": a + b} | |
return ApiResponse(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment