4

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
        }
    }
}
cgrim
  • 4,890
  • 1
  • 23
  • 42

2 Answers2

8

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.

cgrim
  • 4,890
  • 1
  • 23
  • 42
  • I forgot to mention in question description but I've been tried @Nullable and it did not work. The same error occurs. – Jeferson Leonardo Oct 01 '20 at 19:15
  • It must work. I added full example controller class into the answer with example curl calls. Try it. If you still have an error, then the problem must be elsewhere. – cgrim Oct 01 '20 at 19:53
  • My bad. The problem was in the Nullable annotation import. When I set javax.annotation.Nullable it works. Thank u. – Jeferson Leonardo Oct 01 '20 at 20:42
1

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");
}
Matthew Gilliard
  • 9,298
  • 3
  • 33
  • 48