在RESTful API请求中指定资源的字段列表的方法 [英] Way to specify resource's fields list in RESTful API request
问题描述
我在Web服务中拥有RESTful API,其中包含用户,帖子等某种资源.当我请求帖子列表(GET/posts)时,我只想检索帖子数组,其中每个帖子的数据减少了一部分(即主题,作者姓名).当我请求具体帖子(GET/posts/42)时,我想检索帖子对象字段的完整列表,包括大型帖子正文,有关喜欢计数,评论计数的其他信息. 我想有很多方法可以解决这个问题.在我看来,最明显的三个是:
I have RESTful API within a web-service with some kind of resources like users, posts and so on. When I make request for list of posts (GET /posts), I want to retrieve array of posts only with reduced part of data for each post (i.e. subject, author name). When I make request for concrete post (GET /posts/42) I want to retrieve full list of post object fields, including big post body, additional info about likes count, comments count. I suppose it is exists many ways to solve this problem. In my mind, 3 most obvious are:
- 明确指定每个请求点亮的字段 (/posts?fileds = subject,author_name和for /posts/42?fields = subject,body,createaAt,author_name,comments_count,likes_count等).
- 仅当字段列表与默认值不同时才明确指定字段列表 字段列表.
- 指定应排除的字段列表 (或包含)默认字段(如果需要)与默认字段不同.
- Explicitly specify fields lits on every request (/posts?fileds=subject,author_name and for /posts/42?fields=subject,body,createaAt,author_name,comments_count,likes_count,etc...).
- Explicitly specify fields list only if it differs from default fields list.
- Specify fields list that should be excluded (or inlcuded) from (to) default fields set if desired fields set differs from default.
我该如何为客户构建清晰实用的API.我应该选择哪种方式?
I what to build clear and useful API for my customers. Which way should I choose?
推荐答案
我会选择选项2恕我直言.
I'd go for option 2 IMHO.
因此,如果使用者仅请求资源url(/posts/42
),他们将收到默认字段.
So if the consumer just requests the resource url (/posts/42
) they receive the default fields.
然后,消费者可以通过在查询字符串中定义值来更改默认响应,例如:
Then consumers can alter the default response by defining values in the query string like:
/posts/42/fields?subject,author_name
过去,这对我来说效果很好,也是其他一些知名API的工作原理,例如 Facebook
This has worked well for me in the past and is how some other well know APIs work, e.g. Facebook
修改:回头看一下,我将请求更改为:
Edit: Looking back at this I’d change the request to be:
/posts/42?fields=subject,author_name
/post/42
是资源,而不是字段.
/post/42
is the resource, not fields.
这篇关于在RESTful API请求中指定资源的字段列表的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!