alxlx alxlx - 2 months ago 10
reST (reStructuredText) Question

How to design api to retrieve one resource by non-primary key in RESTful style?

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?

Answer

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.