I have this extremely simple API in spring boot,
@RestController
@RequestMapping(value = "/users")
public class UserController {
@Autowired
private IUserRepository userRepository;
@PostMapping()
public UserModel createUser(@RequestBody UserModel user){
return userRepository.save(user);
}
@GetMapping()
public List<UserModel> getUsers(){
return userRepository.findAll();
}
@GetMapping(value = "{id}")
public Optional<UserModel> getUserById(@RequestParam("id") String id) {
return userRepository.findById(id);
}
@GetMapping(value="/searchByName/{name}")
public List<UserModel> requestMethodName(@RequestParam("name") String name) {
return userRepository.findByName(name);
}
}
When I run, it compiles well and throws no error, but when I make get requests it mismatches the request as follows:
When I do: "http://localhost:2202/users" I get the list of all users without problems,
But when I call: "http://localhost:2202/users?id=5e6f5b4d19d83c38af6c648d" I still get the list of all users. When I place a breakpoint in the "getUserById" action of the controller, the break point never hits.
Also, when I call: "http://localhost:2202/users/searchByName?name=Runtebala" I get a 400 Bad Request.
This is driving me crazy, does anyone have a solution ? please
Update @GetMapping value for getUserById
like this :
@GetMapping(value = "/{id}") // add '/' before the parameter
public Optional<UserModel> getUserById(@PathVariable("id") String id) {
return userRepository.findById(id);
}
For requestMethodName
you need to fix the request. Add '/' before name :
"http://localhost:2202/users/searchByName/Runtebala"
And update your method like this :
@GetMapping(value="/searchByName/{name}")
public List<UserModel> requestMethodName(@PathVariable("name") String name) {
return userRepository.findByName(name);
}
If you need to use @RequestParam don't specify the parameter in the Mapping value and just leave your method params with @RequestParam.
Hope it helps, Good Luck !