Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i differentiate between two endpoints, each with one PathVariable?

I'm working on a Spring Boot application. I have the following REST endpoint(s):

 @GetMapping(value = { "/person/{name}", "/person/{age}" })
 public PersonData getPersonData(@PathVariable(required = false) String name,
                                 @PathVariable(required = false) Integer age) {

}

This endpoint can be called with either a name variable or an age variable, however it looks like it can't differentiate between them. If I was to call '.../person/20', it would not call "/person/{age}", but it always calls "/person/{name}".

I know I could make something like:

@GetMapping(value = { "/person/name/{name}", "/person/age/{age}" })

However are there any other way to solve it without adding anything to the path?

like image 350
TheStranger Avatar asked Apr 30 '26 09:04

TheStranger


1 Answers

A path variable is something like a primary key usually.

Like:

/person/{id}

What you try is to search for data and this should be done with query parameters.

Example:

@GetMapping(value = { "/person/{name}", "/person/{age}" })
public PersonData getPersonData(@RequestParam String name,
                                @RequestParam Integer age) {

}

Then you can call it

/person?age=40
/person?name=Peter
like image 121
Simon Martinelli Avatar answered May 02 '26 00:05

Simon Martinelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!