REST - supporting multiple possible identifiers

后端 未结 5 1230
一向
一向 2020-12-13 02:00

For the site I am working on, we are in the process of improving our URLs for one type of resource - specifically, moving away from numerical IDs toward unique, descriptive

5条回答
  •  悲&欢浪女
    2020-12-13 02:19

    I think adding a path segment/prefix is the best answer. Since these are unique secondary keys, this isn't the same as search (which returns a set of items), so using query parameters (which aren't cached) doesn't seem like the best choice.

    Personally, I plan to use a path segment prefix delimited by "=", like "name=" or "email=":

    user/123456
    user/name=john.doe
    user/email=john.doe@john.doe
    

    This is functionally equivalent to adding a path segment (e.g. "user/name/john.doe"), but feels to me like it maps more closely to the conceptual model. Of course, this is an insignificant detail, since RESTful APIs shouldn't specify a fixed URI structure anyway.

    Not using query parameters also allows sub-resources to be accessed naturally:

    user/name=john.doe/inbox/df87bhJXrg63
    

    Frameworks like Java's JAX-RS support using whatever delimiter you want:

    @GET
    @Path("user/{id}")
    User getUser(@PathParam("id") UUID id);
    
    @GET
    @Path("user/name={name}")
    User getUserByName(@PathParam("name") String name);
    
    @GET
    @Path("user/email={email}")
    User getUserByEmail(@PathParam("email") String email);
    

提交回复
热议问题