为 RESTful API 设计返回值 [英] Design return values for RESTful API
问题描述
有很多关于 RESTful 服务的文档.我需要有关返回表示的更多信息.
There is a lot of documentation for RESTful services. I need more Information about the returning representations.
为 RESTful 服务设计返回值的最佳方法是什么?
What is the best way for design the return value for RESTful ervices?
示例:
GET/rest/cars
:列出汽车GET/rest/cars/1234
:ID 为 1234 的汽车
GET /rest/cars
: list with carsGET /rest/cars/1234
: the car with the ID 1234
对于 RESTful 服务:
For RESTful services:
- 返回值(汽车对象)是否应该具有相同的属性?
- detail 对象是否可以拥有比列表对象更多的属性?
- 在哪种情况下对象必须相同?
推荐答案
使用查询参数请求字段子集
您可以在两种情况下返回相同的表示,并支持使用查询参数过滤要返回的字段:
Using query parameters to request a subset of fields
You can return the same representation in both cases and support filtering the fields to be returned with a query parameter:
GET /api/cars?fields=color,year HTTP/1.1
Host: example.com
Accept: application/json
使用自定义媒体类型返回一组预定义的字段
另一种方法是为资源的部分表示定义自定义媒体类型.
Using custom media types to return a predefined set of fields
Another approach is to define a custom media type for a partial representation of your resource.
例如,您可以使用以下一种(或两种)媒体类型来检索资源集合的完整表示:
For example, you could use one of the following (or both) media types to retrieve a full representation of a collection of resources:
GET /api/cars HTTP/1.1
Host: example.com
Accept: application/json
GET /api/cars HTTP/1.1
Host: example.com
Accept: application/vnd.company.full+json
以下内容将返回您的资源的部分表示(您将包含在部分表示中的字段由您决定):
And the following to return a partial representation for your resource (the fields you will include in the partial representation are up to you):
GET /api/cars HTTP/1.1
Host: example.com
Accept: application/vnd.company.partial+json
这篇关于为 RESTful API 设计返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!