I have two unique keys in a table id, userId. I have to create a REST api in spring to get user details if any of the two keys are given as path variables.
The challenge here is we have to create two different endpoints for getting user through id and getting user through userId but use same method for both. Also datatype of id is long and datatype of userId is String in table
So I am trying to do following
the endpoint "/user/{id}" is for userId
@RequestMapping(value = {"/{id}","/user/{id}"}, method=RequestMethod.GET)
public response getUser(@PathVariable("id") String id){
}
But I am unable to figure out how to check whether I got id or userId inside the method. Also is this the right way to do it?
I would use the @RequestMapping
Multiple paths mapped to the same controller method possibility in such a manner.
I suspect that even if you refactor your code to call one single method, you still have to implement some logic to differentiate between the two parameters inside the controller method.
Besides, getUserById()
signature is ambiguous. What the parameter id
means the id
or userId
Having two separate method for what you want to acheive would be more efficient two handle each case properly. Inside each controller method you can use a common logic for the two if you want.
@RequestMapping(value = "/user/{userId}", method=RequestMethod.GET)
public String getUserById(@PathVariable("userId") String userId){
// Common login
}
@RequestMapping(value = "/id", method=RequestMethod.GET)
public String getUserByUserId(@PathVariable("userId") String userId){
// Common login
}
You can even implement for each endpoint validators to check either you @PathVariable is valid or not in case of Long
or String
Here are some references ref1, ref2
You can do this with single method like this:
@RequestMapping(value = {"/{id}", "/user/{userId}"}, method = RequestMethod.GET)
public void getUser(@PathVariable(value = "id", required = false) String id,
@PathVariable(value = "userId", required = false) Long userId) {
if (id != null) {
//TODO stuff for id
}
if (userId != null) {
//TODO stuff for userId
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With