7.2.1 Customizing Parameter Binding

The previous example presented a trivial example that uses the parameters of a method to represent the body of a POST request:

PetOperations.java

  1. @Post
  2. Single<Pet> save(@NotBlank String name, @Min(1L) int age);

The save method when called will perform an HTTP POST with the following JSON by default:

Example Produced JSON

  1. {"name":"Dino", "age":10}

You may however want to customize what is sent as the body, the parameters, URI variables and so on. The @Client annotation is very flexible in this regard and supports the same HTTP Annotations as Micronaut’s HTTP server.

For example, the following defines a URI template and the name parameter is used as part of the URI template, whilst @Body is used declare that the contents to send to the server are represented by the Pet POJO:

PetOperations.java

  1. @Post("/{name}")
  2. Single<Pet> save(
  3. @NotBlank String name, (1)
  4. @Body @Valid Pet pet) (2)
1The name parameter, included as part of the URI, and declared @NotBlank
2The pet parameter, used to encode the body and declared @Valid

The following table summarizes the parameter annotations, their purpose, and provides an example:

Table 1. Parameter Binding Annotations
AnnotationDescriptionExample

@Body

Allows to specify the parameter that is the body of the request

@Body String body

@CookieValue

Allows specifying parameters that should be sent as cookies

@CookieValue String myCookie

@Header

Allows specifying parameters that should be sent as HTTP headers

@Header String contentType

@QueryValue

Allows customizing the name of the URI parameter to bind from

@QueryValue(“userAge”) Integer age

@PathVariable

Used to bind a parameter exclusively from a Path Variable.

@PathVariable Long id

@RequestAttribute

Allows specifying parameters that should be set as request attributes

@RequestAttribute Integer locationId

Type Based Binding Parameters

Some parameters are recognized by their type instead of their annotation. The following table summarizes the parameter types, their purpose, and provides an example:

TypeDescriptionExample

BasicAuth

Allows binding of basic authorization credentials

BasicAuth basicAuth