REST - Partial Resources

2019-05-22 17:35发布

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.

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
}

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,name

where fields says I only want those fields back.

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.

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?

标签: json rest
3条回答
【Aperson】
2楼-- · 2019-05-22 18:22

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

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

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

查看更多
该账号已被封号
3楼-- · 2019-05-22 18:28

Just to extend a bit the two great previous responses about partial responses, you could also consider the header Prefer instead of using the query parameter fields.

See the following links for more details:

Hope it helps you, Thierry

查看更多
干净又极端
4楼-- · 2019-05-22 18:31

What you are talking about is a different representation of the same resource. Both representations are valid, but in my opinion #2 makes more sense, because the response is smaller, and if you don't want to display the values you usually don't need the property names either.

查看更多
登录 后发表回答