4

Original, we have a api GET /users/:id to retrieve a user by its primary key.

Now we need a new api to retrieve a user by its email.

GET /users?email=xx@xx.com seems like to get a collection.

GET /users/byEmail/:email includes a non-noun word byEmail.

Is there any other choice?

a.l.
  • 1,085
  • 12
  • 29
  • 1
    What you are trying to do is not a very good practice. There are many questions like this on Stack Overflow. Please check this: http://stackoverflow.com/questions/11104466/restful-url-to-get-resource-by-different-fields – zilvinas Sep 19 '16 at 10:04

2 Answers2

4

Both approaches you have suggested are valid on their own, but I probably wouldn't do both as it's best to stick with one URI per resource. Another common way to do this is:

/users/id/:id

or

/users/email/:email

I should point out that the choice of query params vs url params or /name/:value vs /:value is not what make a service "RESTful". Put another way, having "pretty" or "readable" URLs does not automatically mean your service is RESTful.

One of the key points of REST is resource identification through a URI i.e. a particular URI will always point to a particular resource. In the case of email, this could probably change (user may want to change their email address) so this url no longer identifies this user at all times.

A more RESTful approach would be to make explicit that this is really a search and not an identifier, and have a URI like this:

/search/users/email/:email

This is more RESTful because this URI always identifies the same resource, namely the search results for this email address. Note that the resource in this case is the search results, not the user resource itself.

tonicsoft
  • 1,736
  • 9
  • 22
1

I like the convention that URIs with / at the end of the path are the collections. So GET /users?email=xx@xx.com returns an item and GET /users/?email=xx@xx.com returns a collection with a single item. But ofc. you don't have to use this convention.

Another options are using /users/:email if you can solve the routing on the server, or /users-by-email/:email or /users/email-:email, etc... It is not important which URI structure you choose as long as your REST API meets with the HATEOAS constraint.

inf3rno
  • 24,976
  • 11
  • 115
  • 197