user4347600
user4347600

Reputation:

How to configure rest controller to accept a path variable that is dynamic?

I have an api call that performs a get like: http://localhost/foo/barCodes?0=XXX&1=ZZZ?2=YYY It can be more or less depending on the user's actions.. For the backend Restcontroller, initially i tried

 @GetMapping("/foo/barCodes")
  public ResponseEntity<List<Food>> getSomeFood(
      @RequestParam String[] codes) { 

but i get error Bad Request', message: "Required request parameter 'codes' for method parameter type String[] is not present". I also looked at pathvariable but those seems to be static.

I did think about parsing out maybe have the values separated by ":" like XXX:ZZZ:YYY or XXX:YYY then that would be one value and I can split it. Is there a different way about it?

Upvotes: 0

Views: 270

Answers (1)

Eugene
Eugene

Reputation: 5975

1. Mapping a Multi-Value Parameter

List of values can be passed via URL like this:

http://localhost:12345/foo/barCodes?codes=firstValue,secondValue,thirdValue

OR

http://localhost:12345/foo/barCodes?codes=firstValue&codes=secondValue&codes=thirdValue

In spring rest controller, they can be received like this:

@GetMapping("/foo/barCodes")
public void getSomeFood(@RequestParam String[] codes) {
   // Handle values here
}

OR

@GetMapping("/foo/barCodes")
public void getSomeFood(@RequestParam List<String> codes) {
   // Handle values here
}

2. Mapping All Parameters

We can also have multiple parameters without defining their names or count by just using a Map. But in this case you need to change GET to POST method.

@PostMapping("/foo/barCodes")
public String getSomeFood(@RequestParam Map<String,String> allParams) {
       // Handle values here    
}

Request json example:

{
    "Par1":"Val1",
    "Par2":"Val2"
}

OR

curl -X POST -F 'Par1' -F 'Val1' http://localhost:12345/foo/barCodes

Upvotes: 2

Related Questions