REST - Partial Resources

2019-05-22 18:09发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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:

  • The specification: http://tools.ietf.org/html/rfc7240
  • Irakli Nadareishvili wrote an awesome blog post on this subject: http://www.freshblurbs.com/blog/2015/06/25/api-representations-prefer.html

Hope it helps you, Thierry



标签: json rest