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:
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?
Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.
First, we're going to create a new Django project named rapid-api-practice. Then, within that project, we will create a new app called api. Although this may seem odd at first, the “Django way” is to house an app, or more than likely multiple apps, within a single “project.”
Django is the web development framework in python whereas the Django Rest Framework is the library used in Django to build Rest APIs. Django Rest Framework is especially designed to make the CRUD operations easier to design in Django.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With