39 java rest json http backbone.js
背景
我们正在构建一个Restful API,它应该将数据对象作为JSON返回.在大多数情况下,返回数据对象很好,但在某些情况下,f.ex.分页或验证,我们需要在响应中添加一些元数据.
到目前为止我们有什么
我们已经包装了所有json响应,例如:
{
"metadata" :{
"status": 200|500,
"msg": "Some message here",
"next": "http://api.domain.com/users/10/20"
...
},
"data" :{
"id": 1001,
"name": "Bob"
}
}
Run Code Online (Sandbox Code Playgroud)
优点
缺点
题
将元数据添加到json响应的最佳做法是什么?
UPDATE
到目前为止,我得到的答案如下:
metadata.status一个返回http协议中的http响应代码(200,500 ...)Dan*_*edo 10
您有几种方法可以在RESTful API中传递元数据:
对于metadata.status,请使用Http状态代码,这就是为什么!如果元数据是指整个响应,则可以将其添加为标题字段.如果元数据仅指代响应的一部分,则必须将元数据嵌入到对象的一部分中.不要将整个响应包装在人工信封中,并将包装器拆分为数据和元数据.
最后,通过您的选择在您的API中保持一致.
一个很好的例子是整个集合的GET与分页.GET/items您可以在自定义标题中返回集合大小和当前页面.标准链接标题中的分页链接:
Link: <https://api.mydomain.com/v1/items?limit=25&offset=25>; rel=next
Run Code Online (Sandbox Code Playgroud)
此方法的问题是,您需要添加引用响应中特定元素的元数据.在这种情况下,只需将其嵌入对象本身.并采用一致的方法......始终将所有元数据添加到响应中.所以回到GET/items,想象每个项目都创建并更新了元数据:
{
items:[
{
"id":"w67e87898dnkwu4752igd",
"message" : "some content",
"_created": "2014-02-14T10:07:39.574Z",
"_updated": "2014-02-14T10:07:39.574Z"
},
......
{
"id":"asjdfiu3748hiuqdh",
"message" : "some other content",
"_created": "2014-02-14T10:07:39.574Z",
"_updated": "2014-02-14T10:07:39.574Z"
}
],
"_total" :133,
"_links" :[
{
"next" :{
href : "https://api.mydomain.com/v1/items?limit=25&offset=25"
}
]
}
Run Code Online (Sandbox Code Playgroud)
请注意,集合响应是一种特殊情况.如果向集合添加元数据,则集合不能再作为数组返回,它必须是包含数组的对象.为什么一个物体?因为您想添加一些元数据属性.
与各个项目中的元数据进行比较.没有任何东西可以包裹实体.您只需向资源添加一些属性即可.
一种惯例是区分控制或元数据字段.您可以使用下划线为这些字段添加前缀.
我们有相同的用例,其中我们需要将分页元数据添加到 JSON 响应。我们最终在 Backbone 中创建了一个可以处理这些数据的集合类型,并在 Rails 端创建了一个轻量级包装器。此示例只是将元数据添加到集合对象中以供视图引用。
所以我们创建了一个像这样的 Backbone Collection 类
// Example response:
// { num_pages: 4, limit_value: 25, current_page: 1, total_count: 97
// records: [{...}, {...}] }
PageableCollection = Backbone.Collection.extend({
parse: function(resp, xhr) {
this.numPages = resp.num_pages;
this.limitValue = resp.limit_value;
this.currentPage = resp.current_page;
this.totalCount = resp.total_count;
return resp.records;
}
});
Run Code Online (Sandbox Code Playgroud)
然后我们在 Rails 端创建了这个简单的类,以便在使用 Kaminari 分页时发出元数据
class PageableCollection
def initialize (collection)
@collection = collection
end
def as_json(opts = {})
{
:num_pages => @collection.num_pages
:limit_value => @collection.limit_value
:current_page => @collection.current_page,
:total_count => @collection.total_count
:records => @collection.to_a.as_json(opts)
}
end
end
Run Code Online (Sandbox Code Playgroud)
你可以在像这样的控制器中使用它
class ThingsController < ApplicationController
def index
@things = Thing.all.page params[:page]
render :json => PageableCollection.new(@things)
end
end
Run Code Online (Sandbox Code Playgroud)
享受。希望你觉得它有用。
| 归档时间: |
|
| 查看次数: |
21153 次 |
| 最近记录: |