我是第一次设计 REST API,所以我认为关于它的设计有一个非常基本的问题。
我希望文件集合返回所有可用文件资源的 ID(或链接),而不是检索完整表示,因为它会包含太多数据。
GET /files # return the full representation of a collection of resources
GET /files/{id} # return the full representation of a single resource
不知道把它拆分成两个不同的资源是否更好:
GET /fileids # return only IDs
GET /files/{id} # return the full representation of a single resource
你的方法是什么?
最佳答案
自定义媒体类型
您可以为资源的完整表示使用自定义媒体类型,并为文件的标识符使用自定义媒体类型。
例如,您可以使用以下一种(或两种)媒体类型来检索文件集合的完整表示:
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
以下媒体类型仅检索文件的标识符:
GET /api/files HTTP/1.1
Host: example.com
Accept: application/vnd.company.id+json
查询字符串参数
或者,您可以支持使用查询字符串参数选择要检索的字段。
使用以下命令检索文件集合的完整表示:
GET /api/files HTTP/1.1
Host: example.com
Accept: application/json
以下仅检索文件的标识符:
GET /api/files?fields=id HTTP/1.1
Host: example.com
Accept: application/json
field
查询参数可以支持以逗号分隔的值列表,允许选择多个字段/属性:GET /api/files?fields=id,name,author HTTP/1.1
Host: example.com
Accept: application/json
关于rest - 检索 ID 集合而不是 REST 中资源的完整表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37456572/