How can I set param as not required in micronaut GET request?

9k views Asked by At

I need to set a param as Not Required in my request.

I tried:

 @Get(value = "/list/{username}")
 HttpResponse<?> list(String username, @QueryValue(value = "actionCode") String actionCode) {
     ...
 }

When I send the request http://localhost:8080/notification/list/00000000000 the following error is thrown:

{
    "message": "Required Parameter [actionCode] not specified",
    "path": "/actionCode",
    "_links": {
        "self": {
            "href": "/notification/list/00000000000",
            "templated": false
        }
    }
}
2

There are 2 answers

3
cgrim On BEST ANSWER

You can define query parameter in Micronaut as optional by javax.annotation.Nullable annotation:

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.QueryValue;
import javax.annotation.Nullable;

@Controller("/sample")
public class SampleController {
    @Get("/list/{username}")
    public String list(
        String username,
        @Nullable @QueryValue String actionCode
    ) {
        return String.format("Test with username = '%s', actionCode = '%s'", username, actionCode);
    }
}

And here are example calls with their results. Call without actionCode:

$ curl http://localhost:8080/sample/list/some-user
Test with username = 'some-user', actionCode = 'null'

Call with actionCode:

$ curl http://localhost:8080/sample/list/some-user?actionCode=some-code
Test with username = 'some-user', actionCode = 'some-code'

As you can see there is no error and it works this way in Micronaut version 1 and also in version 2.

0
Matthew Gilliard On

You can use Optional<String> as the argument type:

@Get(produces = MediaType.TEXT_PLAIN)
public String index(@QueryValue("name") Optional<String> name) {
  return "Hello " + name.orElse("anonymous person");
}