Java Spring REST API with Empty or Optional parameters

Sometimes you need the ability to handle REST API calls with empty parameters. For instance we have following REST API:

@RequestMapping(value = "/getJsonFile")
public String getJsonFile(@RequestParam("instanceType") String instanceType,
                          @RequestParam("repositoryBucket") String repositoryBucket,
                          @RequestParam("ec2HostName") String ec2HostName,
                          @RequestParam("metaData") String metaData) {
    // your code ...

    return jsonFile;
}

So client requests this REST API by following URL:
http://10.0.61.117:8080/getJsonFile?instanceType=APP&repositoryBucket=my-repo&ec2HostName=codeflex&metaData=true

But what if some clients don’t need the last parameter – metaData? So they calling for this URL:
http://10.0.61.117:8080/getJsonFile?instanceType=APP&repositoryBucket=my-repo&ec2HostName=codeflex

Now we have to specify on our server side that metaData parameter is optional.

Here how you do it:

@RequestMapping(value = "/getJsonFile")
public String getJsonFile(@RequestParam("instanceType") String instanceType,
                          @RequestParam("repositoryBucket") String repositoryBucket,
                          @RequestParam("ec2HostName") String ec2HostName,
                          @RequestParam(value = "metaData", required = false) String metaData) {
    // your code ...

    return jsonFile;
}

Alternative approach is to use Java 8 Optional keyword, then you don’t even need to specify required = false

@RequestMapping(value = "/getJsonFile")
public String getJsonFile(@RequestParam("instanceType") String instanceType,
                          @RequestParam("repositoryBucket") String repositoryBucket,
                          @RequestParam("ec2HostName") String ec2HostName,
                          @RequestParam("metaData") Optional<String> metaData) {
    // your code ...

    return jsonFile;
}

3 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.