Pete B.
Pete B.

Reputation: 3286

Naming a GET with alternative query options

Assume you have a REST service that already gets users by id, so the url looks something like

GET /users/{userId}

But you want to create a duplicate web service that gets users by email, so:

GET /users/{email}

Which is better?

Method 1:

Same method:

  /users/{input}
  ...
  if(isEmail(input)) queryByEmail(input);
  else queryById(input);

Method 2:

Different Method:

GET /users/{userId}

GET /usersByEmail/{email}

Upvotes: 0

Views: 52

Answers (3)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57279

Which is better?

REST doesn't care; from the perspective of the client, the URI is opaque. The clients concerns are following links/submitting forms/completing templates.

Information encoded into the URI is done at the server's discretion and for its own exclusive use.

So you can use any spelling you like. As a rule, it's a good idea to conform to local spelling conventions (in much the same way that your variable names in code should conform to your coding conventions). But your clients shouldn't need to know the details of those conventions.

/users/{input}
...
if(isEmail(input)) queryByEmail(input);
else queryById(input);

Note that you aren't necessarily deeply committed to one approach; that's part of the point of decoupling the identifiers from the representations. For instance, your implementation could just as easily look like

/users/{input}
...
if(isEmail(input)) redirectTo(/users/email/{input});
else redirectTo(/users/id/{input});

which allows clients that have bookmarked the original URI to arrive at the correct resource.

Upvotes: 0

tereško
tereško

Reputation: 58444

Since there is no actual overlap between email addresses and IDs. I would just use same endpoint for both. Especially if GET /users/{id} is already a published interface.

So, I would go with 1st method.

GET /users/{identifier}

Then on the API server you have to add a small check, whether {identifier} is a number or not.

I would also like to note, that "pretty URLs" do not make it REST :) You probably will want to watch this lecture: https://www.youtube.com/watch?v=pspy1H6A3FM

Upvotes: 2

Danie
Danie

Reputation: 464

My personal preference would be,

GET /users/id/{id}
GET /users/email/{email}

But it all depends on what you the rest endpoints to look like.

Upvotes: 1

Related Questions