比如,对于资源 Post, 请求一个资源的的地址为 http://example.com/posts/1 请求一个命名集合(collection)的资源,比如最新的 posts,可以用 http://example.com/posts/recent
如果我想请求多个离散的资源,比如 id=2, id=12, id=13, id=4,可以访问 http://example.com/posts/:id 这个接口 4 次,但这样多次请求,效率不高;在实际使用中,结合其他接口,很有可能出现类似于 SQL 中的 1+N 问题。所以希望在一次请求中,返回满足要求的结果。
SO 上有一个讨论: How to construct a REST API that takes an array of id's for the resources ,提到可以用类似
http://example.com/posts/?id=2,12,14,4
这种形式的接口。但是根据Query String的规范:
Letters (A-Z and a-z), numbers (0-9) and the characters '.','-','~' and '_' are left as-is SPACE is encoded as '+' or %20[citation needed] All other characters are encoded as %FF hex representation with any non-ASCII characters first encoded as UTF-8 (or other specified encoding)
所以 Query String 里的,
应该用%2C
代替,所以上面的 URL 应为
http://example.com/posts?id=2%2C12%2C14%2C4
这样看起来很别扭。有没有其他的解决方案呢?