[关闭]
@lonelinsky 2016-05-17T11:17:51.000000Z 字数 3888 阅读 735

TastyPie Restful API使用文档

Tastypie Restful-API


Restful API通过使用HTTP的Method关键字完成了前端和数据库数据的交互,实现了一套比较标准的访问接口,此文主要用于描述基于TastyPie实现的Restful API的使用指南。主要分为增删查改四个部分。

这个链接用于获取API的相关信息,会给出所有的可用接口以及相关接口的语法说明。
示例:http://uc.dreamlabchina.com/api/v1/

基础知识:

METHOD:POST
访问地址:list_endpoint, detail_point
参数说明:
JSON类型数据,具体可以参考章节返回的数据格式 (id 和 resource_uri不用填)
返回说明:
正确的话会返回状态码 201 CREATED
错误的话会返回其他错误

特别说明:
默认建议访问list_endpoint,会自动生成ID,如果使用detail_endpoint则会使用自定义ID
如果需要新增foreign_key一类的字段,请使用如下形式:

  1. ToOneField: user:"/api/v1/user/1/"
  2. ToManyFieldusers:["/api/v1/user1", "/api/v1/user/2"]

ajax请求示例:

  1. $.ajax({
  2. url: 'http://uc.dreamlabchina.com/api/v1/block/',
  3. data: JSON.stringify({'address':'TEST', 'name':'TEST'}),
  4. method: 'POST',
  5. dataType: 'json',
  6. contentType: 'application/json',
  7. complete: function (xhr, textStatus) {
  8. console.log("complete");
  9. console.log(textStatus);
  10. console.log(xhr.status);
  11. console.log(xhr.getResponseHeader('Location')); //resource uri.
  12. }
  13. });

METHODDELETE
访问地址:detail_endpoint, list_endpoint
参数说明
无需参数
返回说明
删除成功返回:Status 204 NO CONTENT
如果被删除东西不存在返回:404 NOT FOUND
其他返回其他错误

特别说明
访问detail_endpoint会删除当前entry,访问list_endpoint会删除所有enties

ajax请求示例:

  1. $.ajax({
  2. url: 'http://uc.dreamlabchina.com/api/v1/block/9/',
  3. method: 'DELETE',
  4. dataType: 'json',
  5. contentType: 'application/json',
  6. complete: function (xhr, textStatus) {
  7. console.log("complete");
  8. console.log(textStatus);
  9. console.log(xhr.status);
  10. }
  11. });

METHODGET
访问地址:detail_endpoint, list_endpoint
参数说明
支持filter,order_by, 具体可以参考django的过滤条件

METHOD: PUT PATCH
访问地址: detail_endpoint
参数说明:

返回说明

特别说明
如更改关联字段应该想章节的filter条件一样写。

ajax请求示例:

  1. $.ajax({
  2. url: 'http://uc.dreamlabchina.com/api/v1/block/8/',
  3. method: 'PATCH',
  4. data: JSON.stringify({'build_count':10}),
  5. dataType: 'json',
  6. contentType: 'application/json',
  7. complete: function (xhr, textStatus) {
  8. console.log("complete");
  9. console.log(textStatus);
  10. console.log(xhr.status);
  11. }
  12. });

code snippets

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注