REST-部分资源 [英] REST - Partial Resources

查看:95
本文介绍了REST-部分资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在REST设计中常见的是允许返回部分资源.在这种情况下;我想允许用户仅指定要在该资源的JSON表示中返回的资源的某些字段.

It's common in a REST design to allow partial resources to be returned. In this case; I want to allow the user specify only certain fields of a resource to be returned in the JSON representation of that resource.

例如,假设我们有一个资源Person:

For example lets say we have a resource Person:

{
   "id": 12,
   "name":{
          "first":"Angie",
          "last": "Smith",
          "middle": "joy",
          "maiden": "crowly",
    },
    "address": {
          "street": "1122 Something St.",
          ..and so on...
    },
... and so on
}

可以说参数列表很长.可以说我有一个API使用者,在创建API设计之初,他们只想要id和name.firstfirst这样的几个字段.我假设允许这样的事情很普遍:

Lets say that list of params is pretty long. And lets say I have an API consumer who at the beginning of creating the API design wants only a couple fields like id and name.first back. I'm assuming it's common to allow something like this:

/person?fields = id,名称

/person?fields=id,name

其中的字段表示我只希望返回这些字段.

where fields says I only want those fields back.

我的问题是,那么Person资源应该返回所有包含null的字段,而返回带有值的那些字段,还是应该返回仅包含id和name字段的Person表示形式,然后从字面上动态删除所有其他参数?后端.

The question I have is, should then the Person resource return all fields with nulls and just those fields with values OR should it just return the Person representation with only fields id and name and you literally remove all the other params dynamically from the backend.

看起来像#2看起来更干净,但是在REST中这样做还是有意义的呢?还是人们通常返回所有其他字段(以确保我们在结构/架构方面保持表示的一致性/可靠性)与空吗?

Seems like #2 is cleaner, but does it make sense to do that in REST, or do people normally return all other fields (to make sure we're keeping the representation in terms of structure/schema consistent/reliable) with nulls?

推荐答案

正如您所建议的那样,选项2更干净,是的,在REST中这样做很有意义.

As you suggested, option 2 is cleaner and YES it makes sense to do that in REST.

添加null会打败部分响应的目的,因为它会使响应主体比实际需要的要大.

Adding null defeats part of the purpose of partial responses as it makes the response body larger than it needs to be.

您描述的用例示例显示在Google Developer Forum上;在部分响应部分.

An example of the use case you described is shown on the Google Developer Forum; in the Partial Response section.

这篇关于REST-部分资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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