为Django应用程序创建REST API [英] Creating a REST API for a Django application

查看:116
本文介绍了为Django应用程序创建REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被赋予了一个任务,我必须使用Django技术创建一个应用程序API(REST)。我只需要能够从多个模型中读取(GET)条目,加入它们,并使用JSON格式(一个或多个对象)返回它们。

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.

由于这是我第一次创建一个API,而是我我不太喜欢Django,我可以请你一些指导。

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

如我所见,这两个使您能够快速设置您的应用程序的API。但是我可以使用其中一个创建一个自定义的JSON格式吗?还是有另一种方法?

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?

推荐答案

使用Tastypie: -



models.py

class User(Document):
    name = StringField()

api.py来自tastypie_mongoengine的资源


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())

strong> Javascript(jQuery)

Javascript (jQuery)

此示例是GET请求:

$(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")                                  
       }
    })
})

对于POST请求,将类型更改为 POST 并以正确格式发送数据

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

有关详细信息,请参阅 Tastypie文档

For more details, see the Tastypie docs

这篇关于为Django应用程序创建REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆