检索 ID 集合而不是 REST 中资源的完整表示 [英] Retrieving a collection of IDs instead of the full representation of a resource in REST
问题描述
我是第一次设计 REST API,所以我认为关于它的设计有一个非常基本的问题.
I'm designing a REST API for the first time, so I have what I consider a quite basic question about its design.
我希望文件集合返回所有可用文件资源的 ID(或链接),而不是检索完整的表示,因为它会包含太多数据.
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
您的方法是什么?
推荐答案
自定义媒体类型
您可以为资源的完整表示使用自定义媒体类型,并为文件的标识符使用自定义媒体类型.
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
field
查询参数可以支持以逗号分隔的值列表,允许选择多个字段/属性:
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
这篇关于检索 ID 集合而不是 REST 中资源的完整表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!