Reputation: 616
I have the API route /api/users/:user_id
, which takes a number as a parameter.
I want to have now the same route, but taking the username instead of the id, like this: /api/users/:username
.
In my code, I have the route set up as /api/users/:user
and I check the user
URI parameter and do different actions if it is a number or a string.
Is it good practice / efficient to have the same route, but with a different parameter type? Both the username and user id's are unique.
It works, I just want to know if this is a practical solution, or if I should do separate routes.
Upvotes: 0
Views: 1485
Reputation: 1506
Solution
Make Parameter value as string and send one Request parameter as additional flag which describe request mode.
/api/users/:user_key?type=boolean
> true
(default) userid & false
for username or vice versa.
Modify your api which then can answer two different apis
/api/users/user/userid/:id
& /api/users/user/username/:name
Recommended
Above can resolve your issue. But is not recommended way of dealing with fetching user profile information using REST api. Presuming you will introduced user authentication in you rest application.
/api/users/me
: this will fetch user info of the once who is currently logged with respect to that session/token.api/users/:id
: this will fetch fetch specific user infoapi/users?filters={username=some_username, }
: this will fetch info of those users which have username matching with given filter.Upvotes: 0
Reputation: 91585
It isn't really "good practice" to share a route parameter on a route, but as long as the IDs and usernames are both unique, you should be fine. Both act as unique identifiers for a user so both can be used to find the user in that route.
You can accept both the ID and username as the same parameter by first making the route param more permissive. Next, you can use the following (pseudo) query to look up whether that param matches the ID or the username:
SELECT id, name FROM users WHERE id={param} OR username={param}
Remember to pass that param in as a real query parameter; do NOT simply concatenate strings. Doing so will open you up to an SQL injection attack.
Upvotes: 0
Reputation: 130977
Assuming that both IDs and usernames are unique, it's valid solution.
Regarding implementation, you could use a regular expression to match the user identifier and check if it's an ID or a username.
Upvotes: 1
Reputation: 118
we solved it by parsing the path variable.
psuedo code
long id;
String name;
try{
id = parselong(input);
}catch(parse exception){
name = input;
}
findbynameorid(id,name)
select * from customer where name = ? or id = ?
Upvotes: 1