在RESTful API请求中指定资源的字段列表的方法 [英] Way to specify resource's fields list in RESTful API request

查看:454
本文介绍了在RESTful API请求中指定资源的字段列表的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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:

  1. 明确指定每个请求点亮的字段 (/posts?fileds = subject,author_name和for /posts/42?fields = subject,body,createaAt,author_name,comments_count,likes_count等).
  2. 仅当字段列表与默认值不同时才明确指定字段列表 字段列表.
  3. 指定应排除的字段列表 (或包含)默认字段(如果需要)与默认字段不同.
  1. 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...).
  2. Explicitly specify fields list only if it differs from default fields list.
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆