REST 中的子资源和路径变量冲突?

Subresource and path variable conflicts in REST?

设计一个路径解析可能有歧义的 REST API 是否被认为是不好的做法?例如:

GET /animals/{id}   // Returns the animal with the given ID
GET /animals/dogs   // Returns all animals of type dog

好吧,那是人为的,因为您实际上会做 GET /dogs,但希望它能说明我的意思。从路径解析的角度来看,您似乎不知道自己是在寻找具有 id="dogs" 的动物还是仅具有 dogs

的动物

具体来说,我想知道 Jersey 是否会在解决此问题时遇到任何问题。如果您知道 id 是整数怎么办?

"Specifically, I'm interested in whether Jersey would have any trouble resolving this"

不,这不是问题。如果您查看 the JAX-RS spec § 3.7.2,您将看到将请求与资源方法匹配的算法。

[E is the set of matching methods]...

Sort E using the number of literal characters in each member as the primary key (descending order), the number of capturing groups as a secondary key (descending order) and the number of capturing groups with non-default regular expressions (i.e. not ‘([^ /]+?)’) as the tertiary key (descending order)

所以基本上是说文字字符的数量是排序的主键(注意它是短路的;你赢了主,你赢了)。因此,例如,如果请求转到 /animals/cat@Path("/animals/dogs") 显然不在集合中,因此我们无需担心。但是如果请求是 /animals/dogs,那么这两种方法都会在集合中。然后根据文字字符的数量对该集合进行排序。由于 @Path("/animals/dogs")@Path("/animals/") 具有更多的文字字符,因此前者获胜。捕获组 {id} 不计入文字字符。

"What if you knew the id to be an integer?"

捕获组允许正则表达式。所以你可以使用@Path("/animals/{id: \d+}")。任何不是数字的东西都不会通过并导致 404,当然除非它是 /animals/dogs.