Retrieving a collection of IDs instead of the full

2019-02-25 06:07发布

I'm designing a REST API for the first time, so I have what I consider a quite basic question about its design.

I would like the files collection to return an ID (or a link) of all available file resources instead of retrieving the full representation because it would be too much data.

GET /files        # return the full representation of a collection of resources
GET /files/{id}   # return the full representation of a single resource 

I don't know if it is better to split it in two different resources:

GET /fileids      # return only IDs
GET /files/{id}   # return the full representation of a single resource

What would be your approach?

标签: rest
2条回答
干净又极端
2楼-- · 2019-02-25 06:49

Just do it.

I would call it a standard RESTful API design pattern to have an abbreviated resource representation in your collections resource and the full representation only on your entity resource.

So /files would return something like:

[
  {
    name: "foo",
    url: "example.org/files/3321"
  },
  {
    name: "bar",
    url: "example.org/files/3192910"
  }
]

While /files/3321 returns the full file representation

{
  name: "foo",
  self: "example.org/files/3321"
  encoding: "UTF-8",
  type: "xml-document"
}
查看更多
干净又极端
3楼-- · 2019-02-25 06:56

Custom media type

You could have a custom media type for the full representation of the resource and a custom media type for the identifiers of the files.

For example, you could use one of the following (or both) media types to retrieve a full representation of a collection of files:

GET /api/files HTTP/1.1
Host: example.com
Accept: application/json
GET /api/files HTTP/1.1
Host: example.com
Accept: application/vnd.company+json

And the following media type to retrieve only the identifiers of the files:

GET /api/files HTTP/1.1
Host: example.com
Accept: application/vnd.company.id+json

Query string parameter

Alternatively, you could support selecting the fields to be retrieved with a query string parameter.

Use the following to retrieve the full representation of a collection of files:

GET /api/files HTTP/1.1
Host: example.com
Accept: application/json

And the following to retrieve only the identifiers of the files:

GET /api/files?fields=id HTTP/1.1
Host: example.com
Accept: application/json

The field query parameter could support a list of values separated by commas, allowing the selection of multiple fields/properties:

GET /api/files?fields=id,name,author HTTP/1.1
Host: example.com
Accept: application/json
查看更多
登录 后发表回答