1

I'm trying to create a restful API (using Spring Boot v2.0.0.Release), I want there to be one endpoint but I'd like there to be two possible uses:

GET /time - outputs current time (e.g. linux epoch in seconds)
GET /time?delta=100000 (time adjusted by the delta in seconds e.g. +ve=future -ve=past)

Firstly is this possible? and secondly does anyone have a code example?

your help is much appreciated

5 Answers5

1

Thanks for your advice, I found that this worked for me. It needed the defaultValue to be added.

@RequestMapping(value = "/time",
                produces = { "text/plain" },
                method = RequestMethod.GET)
public ResponseEntity<String> getTime(@RequestParam(value = "delta",
                                                     required = false,
                                                     defaultValue = "0")
                                                     long delta) {
    if (0L == delta) {
        return new ResponseEntity<String>(calcTime(), HttpStatus.OK);
    }
    else {
        return new ResponseEntity<String>(calcTime(delta), HttpStatus.OK);
    }
}
0

No it is not possible. Why dont you make one endpoint with optional parameters?

Check for other answers for similar questions :

Spring MVC using same path on endpoints to return different content?

Two GET methods with different query parameters : REST

Emre Savcı
  • 3,034
  • 2
  • 16
  • 25
0

You can do something like with Java 8 and Spring assuming return type String

@GetMapping("/time")
public String getTime(@RequestParam Optional<Integer> delta) {
   //...
}

or

@RequestMapping("/time")
public String getTime(@RequestParam Optional<Integer> delta) {
    //...
}
user3470953
  • 11,025
  • 2
  • 17
  • 18
0

You can also do the following aside from Java 8's Optional @RequestParam: Pass the required=false param in @RequestParam

@RestController
class MyClass {

@RequestMapping("/time")
public MyType myEndpoint(@RequestParam(required=false) Integer delta) {
   // if delta is null then it hasn't been provided
}
dimitrisli
  • 20,895
  • 12
  • 59
  • 63
0

Yes this is indeed possible. It seems like you want a single endpoint but with an optional delta parameter.

To achieve this you only need a single @RequestMapping annotation on your method, and all the Spring ceremony goes on the parameter, e.g.:

@RequestMapping(value = “/time”)
public TimeResponse time(@RequestParam(required = false) Integer delta) {
     if (delta == null) { 
          // default case
     }
          // case where delta is present 
}
slowbug
  • 26
  • 3