Subhendu Mahanta
Subhendu Mahanta

Reputation: 1011

Optional @PathVariable in Spring based rest call

I am using Spring boot 2.2.2 with java 1.8. I have a rest end point /getViewAnalyticsByDimension of post type. Now to accommodate a feature I need to change the api to /getViewAnalyticsByDimension/{priceAgreementId}. I want to declare path variable priceAgreementId as optional. But when I post the request to /getViewAnalyticsByDimension when there is no price agreement id from Postman it is not able to find the controller method. I can ask my frontend counter-part to send "blank" when there is no priceAgreementId and the actual priceAgreementId when it is available. But that is not elegant.

Upvotes: 1

Views: 2319

Answers (2)

deepakchethan
deepakchethan

Reputation: 5600

You can have multiple request mappings for a given method. So in your case you can do something as follows to make it work with and without path variable:

@RequestMapping(value = {"/getViewAnalyticsByDimension", "/getViewAnalyticsByDimension/{priceAgreementId}"}")
public Object getObject(@PathVariable Optional<Object> priceAgreementId) {
   //...
}

If you are using a legacy version of spring you can have two different methods:

@RequestMapping(value = "/getViewAnalyticsByDimension/{priceAgreementId}")
public Object getObject(@PathVariable(name = "priceAgreementId") Object priceAgreementId) {
    //...        
}

@RequestMapping(value = "/getViewAnalyticsByDimension")
public Object getObject() {
    //...
}

You can checkout https://www.baeldung.com/spring-optional-path-variables more info

Upvotes: 6

Dhwanil Patel
Dhwanil Patel

Reputation: 2573

You have to modify your method following way,

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
public class Test {

  @RequestMapping(value = {"/getViewAnalyticsByDimension", "/getViewAnalyticsByDimension/{priceAgreementId}"})
  public Object getObject(@PathVariable(required = false) Optional<String> priceAgreementId) {
    if (priceAgreementId.isPresent()) {
      // do something
    } else {
      // do something else
    }
    return something;
  }
}

I checked both URLs accessible, (It's just an example)

http://localhost:8888/getViewAnalyticsByDimension

http://localhost:8888/getViewAnalyticsByDimension/5

Upvotes: 0

Related Questions