How to pass optional query parameters with groovy?

Viewed 1421

I would like to pass optional params to url using micronaut with groovy. I did lots of research but was not able to find any relevant answer.

@Get('/product/{country}/?

I would like to pass in sort and date as optional parameters to this url. Appreciate your help.

2 Answers

You can pass optional sort and date parameters as query values like this:

@Controller('/')
@CompileStatic
class WithOptionalParameterController {
    @Get('/product/{country}{?sort,date}')
    String productsForCountry(String country, 
                              @Nullable @Pattern(regexp = 'code|title') String sort, 
                              @Nullable String date) {
        "Products for $country sorted by $sort and there is also date $date."
    }
}

And it can be called this way with sort and date specified:

$ curl 'http://localhost:8080/product/chile?sort=code&date=23.3.2020'
Products for chile sorted by code and there is also date 23.3.2020.

Or without date:

$ curl 'http://localhost:8080/product/chile?sort=code'
Products for chile sorted by code and there is also date null.

Or without sort and date:

$ curl 'http://localhost:8080/product/chile'
Products for chile sorted by null and there is also date null.

Example for POST where you have to add @QueryValue annotation for query parameters:

@Consumes([MediaType.TEXT_PLAIN])
@Post('/product/{country}{?sort,date}')
String productsForCountry(String country, 
                          @Nullable @Pattern(regexp = 'code|title') @QueryValue String sort,
                          @Nullable @QueryValue String date,
                          @Body String body) {
    "Products for $country sorted by $sort and there is also date $date. Body is $body."
}

And it can be called this way:

$ curl -X POST 'http://localhost:8080/product/chile?sort=code&date=23.3.2020' -H "Content-Type: text/plain" -d 'some body'
Products for chile sorted by code and there is also date 23.3.2020. Body is some body.

use Optional annotation , like

@Get("/optional")
String optional(@QueryValue Optional<Integer> max) {
  return "Parameter Value: " + max.orElse(10);
}
Related