Creating a REST API for a Django application

django, python, rest

Solution

Using Tastypie: --

models.py

class User(Document):
    name = StringField()

api.py

from tastypie import authorization
from tastypie_mongoengine import resources
from project.models import *
from tastypie.resources import *

class UserResource(resources.MongoEngineResource):
class Meta:
    queryset = User.objects.all()
    resource_name = 'user'
    allowed_methods = ('get', 'post', 'put', 'delete','patch')
    authorization = authorization.Authorization()

url.py

from tastypie.api import Api
from projectname.api import *

v1_api = Api(api_name='v1')
v1_api.register(UserResource())

Javascript (jQuery)

This example is of a GET request:

$(document).ready(function(){
    $.ajax({
       url: 'http://127.0.0.1:8000/api/v1/user/?format=json',
       type: 'GET',                   
       contentType: 'application/json',
       dataType: 'json',
       processData: false,
       success: function(data){
           alert(data)
       //here you will get the data from server
       },
       error: function(jqXHR, textStatus, errorThrown){
              alert("Some Error")                                  
       }
    })
})

For a POST request, change the type to `POST` and send the `data` in proper format

For more details, see the Tastypie docs

Problem

I was given an assignment where I have to create an application API (REST) using the Django technology. I only need to be able to read (GET) the entries from multiple models, join them, and return them using the JSON format (one or more objects). The json schema and an example of an appropriate json file were already given to me. Since this is my first time creating an API and I'm not very familliar with Django, I would kindly ask you for some guidance. I googled up two frameworks which seem to be the most popular: - Tastypie - Django REST framework As I've seen these two enable you to quickly setup your API for your application. But can I create a custom JSON format using one of them or is there another way of doing this?

Original source