Home > Software engineering >  How to handle two endpoints in spring boot
How to handle two endpoints in spring boot

Time:06-11

I have written request two end points. Both are same only difference in second end point is added version like:

  • 1st endpoint {name}/{id}
  • 2nd endpoint /v2/{name}/{id}

It is working fine when i am calling with complete end point with complete path but when i am calling second endpoint by removing last path then it is calling 1st end point instead of calling 2nd endpoint

@RestController
@RequestMapping(value = "cpi/can")
public class Controller {

    @RequestMapping(value = "{vin}/{can}/{val}",method = RequestMethod.GET)
    public String get(@PathVariable(value = "vin",required=true) String vin,
              @PathVariable(value = "can", required = true) String cantype,
              @PathVariable(value = "val", required = true) String val) {
        return "THIS IS WORKING";
    }
    
    @RequestMapping(value = "/v2/{vin}/{can}/{val}",method = RequestMethod.GET)
    public String get1(@PathVariable(value = "vin",required=true) String vin,
              @PathVariable(value = "can", required = true) String cantype,
              @PathVariable(value = "val", required = true) String val) {
        return "THIS IS WORKING in V2";
    }

}

If i am calling second endpoint like by removing last value /v2/111/222/ then it is hitting first endpoint. I want to call second endpoint even if i remove the last variable. And i must use path variables. I cant change it to request parameters. It is my requirement

CodePudding user response:

Version 1 API: {vin}/{can}/{val}

Version 2 API: /v2/{vin}/{can}/{val}

As you specified, you are calling API /v2/111/222/, this does not fulfill v2 API specification as the 3rd path variable(val) is not present. v1 is fulfilling the request as v2 maps to {vin}, 111 maps to {can} and 222 maps to {val}.

Solution: Use v1/{vin}/{can}/{val} for version 1 API.

CodePudding user response:

This happens because v2 string matches vin variable in first endpoint. You can add a regular expression to prevent this behavior

Variant 1

Specify the minimum length for vin variable

@GetMapping("{vin:.{10,}}/{can}/{val}")

Variant 2

Variable vin must not be equal v2

@GetMapping("{vin:^(?!(?:v2)\$). \$}/{can}/{val}")

  • Related