7.3.1 Customizing Parameter Binding
The previous example presented a simple example using method parameters to represent the body of a POST
request:
PetOperations.java
@Post
@SingleResult
Publisher<Pet> save(@NotBlank String name, @Min(1L) int age);
The save
method performs an HTTP POST
with the following JSON by default:
Example Produced JSON
{"name":"Dino", "age":10}
You may however want to customize what is sent as the body, the parameters, URI variables, etc. 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 declares that the contents to send to the server are represented by the Pet
POJO:
PetOperations.java
@Post("/{name}")
Mono<Pet> save(
@NotBlank String name, (1)
@Body @Valid Pet pet) (2)
1 | The name parameter, included as part of the URI, and declared @NotBlank |
2 | The pet parameter, used to encode the body and declared @Valid |
The following table summarizes the parameter annotations and their purpose, and provides an example:
Annotation | Description | Example |
---|---|---|
Specifies the parameter for the body of the request |
| |
Specifies parameters to be sent as cookies |
| |
Specifies parameters to be sent as HTTP headers |
| |
Customizes the name of the URI parameter to bind from |
| |
Binds a parameter exclusively from a Path Variable. |
| |
Specifies parameters to be set as request attributes |
|
Always use @Produces or @Consumes instead of supplying a header for Content-Type or Accept . |
Type-Based Binding Parameters
Some parameters are recognized by their type instead of their annotation. The following table summarizes these parameter types and their purpose, and provides an example:
Type | Description | Example |
---|---|---|
Binds Basic Authorization credentials |
|
Custom Binding
The ClientArgumentRequestBinder API binds client arguments to the request. Custom binder classes registered as beans are automatically used during the binding process. Annotation-based binders are searched for first, with type-based binders being searched if a binder was not found.
This is an experimental feature in 2.1 and subject to change! One limitation of binding is that binders may not manipulate or set the request URI because it can be a combination of many arguments. |
Binding By Annotation
To control how an argument is bound to the request based on an annotation on the argument, create a bean of type AnnotatedClientArgumentRequestBinder. Any custom annotations must be annotated with @Bindable.
In this example, see the following client:
Client With @Metadata Argument
@Client("/")
public interface MetadataClient {
@Get("/client/bind")
String get(@Metadata Map<String, Object> metadata);
}
Client With @Metadata Argument
@Client("/")
interface MetadataClient {
@Get("/client/bind")
String get(@Metadata Map metadata)
}
Client With @Metadata Argument
@Client("/")
interface MetadataClient {
@Get("/client/bind")
operator fun get(@Metadata metadata: Map<String, Any>): String
}
The argument is annotated with the following annotation:
@Metadata Annotation
import io.micronaut.core.bind.annotation.Bindable;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Documented
@Retention(RUNTIME)
@Target(PARAMETER)
@Bindable
public @interface Metadata {
}
@Metadata Annotation
import io.micronaut.core.bind.annotation.Bindable
import java.lang.annotation.Documented
import java.lang.annotation.Retention
import java.lang.annotation.Target
import static java.lang.annotation.ElementType.PARAMETER
import static java.lang.annotation.RetentionPolicy.RUNTIME
@Documented
@Retention(RUNTIME)
@Target(PARAMETER)
@Bindable
@interface Metadata {
}
@Metadata Annotation
import io.micronaut.core.bind.annotation.Bindable
import kotlin.annotation.AnnotationRetention.RUNTIME
import kotlin.annotation.AnnotationTarget.VALUE_PARAMETER
@MustBeDocumented
@Retention(RUNTIME)
@Target(VALUE_PARAMETER)
@Bindable
annotation class Metadata
Without any additional code, the client attempts to convert the metadata to a string and append it as a query parameter. In this case that isn’t the desired effect, so a custom binder is needed.
The following binder handles arguments passed to clients that are annotated with the @Metadata
annotation, and mutate the request to contain the desired headers. The implementation could be modified to accept more types of data other than Map
.
Annotation Argument Binder
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.convert.ArgumentConversionContext;
import io.micronaut.core.naming.NameUtils;
import io.micronaut.core.util.StringUtils;
import io.micronaut.http.MutableHttpRequest;
import io.micronaut.http.client.bind.AnnotatedClientArgumentRequestBinder;
import io.micronaut.http.client.bind.ClientRequestUriContext;
import org.jetbrains.annotations.NotNull;
import jakarta.inject.Singleton;
import java.util.Map;
@Singleton
public class MetadataClientArgumentBinder implements AnnotatedClientArgumentRequestBinder<Metadata> {
@NotNull
@Override
public Class<Metadata> getAnnotationType() {
return Metadata.class;
}
@Override
public void bind(@NotNull ArgumentConversionContext<Object> context,
@NonNull ClientRequestUriContext uriContext,
@NotNull Object value,
@NotNull MutableHttpRequest<?> request) {
if (value instanceof Map) {
for (Map.Entry<?, ?> entry: ((Map<?, ?>) value).entrySet()) {
String key = NameUtils.hyphenate(StringUtils.capitalize(entry.getKey().toString()), false);
request.header("X-Metadata-" + key, entry.getValue().toString());
}
}
}
}
Annotation Argument Binder
import io.micronaut.core.annotation.NonNull
import io.micronaut.core.convert.ArgumentConversionContext
import io.micronaut.core.naming.NameUtils
import io.micronaut.core.util.StringUtils
import io.micronaut.http.MutableHttpRequest
import io.micronaut.http.client.bind.AnnotatedClientArgumentRequestBinder
import io.micronaut.http.client.bind.ClientRequestUriContext
import org.jetbrains.annotations.NotNull
import jakarta.inject.Singleton
@Singleton
class MetadataClientArgumentBinder implements AnnotatedClientArgumentRequestBinder<Metadata> {
final Class<Metadata> annotationType = Metadata
@Override
void bind(@NotNull ArgumentConversionContext<Object> context,
@NonNull ClientRequestUriContext uriContext,
@NotNull Object value,
@NotNull MutableHttpRequest<?> request) {
if (value instanceof Map) {
for (entry in value.entrySet()) {
String key = NameUtils.hyphenate(StringUtils.capitalize(entry.key as String), false)
request.header("X-Metadata-$key", entry.value as String)
}
}
}
}
Annotation Argument Binder
import io.micronaut.core.convert.ArgumentConversionContext
import io.micronaut.core.naming.NameUtils
import io.micronaut.core.util.StringUtils
import io.micronaut.http.MutableHttpRequest
import io.micronaut.http.client.bind.AnnotatedClientArgumentRequestBinder
import io.micronaut.http.client.bind.ClientRequestUriContext
import jakarta.inject.Singleton
@Singleton
class MetadataClientArgumentBinder : AnnotatedClientArgumentRequestBinder<Metadata> {
override fun getAnnotationType(): Class<Metadata> {
return Metadata::class.java
}
override fun bind(context: ArgumentConversionContext<Any>,
uriContext: ClientRequestUriContext,
value: Any,
request: MutableHttpRequest<*>) {
if (value is Map<*, *>) {
for ((key1, value1) in value) {
val key = NameUtils.hyphenate(StringUtils.capitalize(key1.toString()), false)
request.header("X-Metadata-$key", value1.toString())
}
}
}
}
Binding By Type
To bind to the request based on the type of the argument, create a bean of type TypedClientArgumentRequestBinder.
In this example, see the following client:
Client With Metadata Argument
@Client("/")
public interface MetadataClient {
@Get("/client/bind")
String get(Metadata metadata);
}
Client With Metadata Argument
@Client("/")
interface MetadataClient {
@Get("/client/bind")
String get(Metadata metadata)
}
Client With Metadata Argument
@Client("/")
interface MetadataClient {
@Get("/client/bind")
operator fun get(metadata: Metadata?): String?
}
Without any additional code, the client attempts to convert the metadata to a string and append it as a query parameter. In this case that isn’t the desired effect, so a custom binder is needed.
The following binder handles arguments passed to clients of type Metadata
and mutate the request to contain the desired headers.
Typed Argument Binder
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.convert.ArgumentConversionContext;
import io.micronaut.core.type.Argument;
import io.micronaut.http.MutableHttpRequest;
import io.micronaut.http.client.bind.ClientRequestUriContext;
import io.micronaut.http.client.bind.TypedClientArgumentRequestBinder;
import jakarta.inject.Singleton;
@Singleton
public class MetadataClientArgumentBinder implements TypedClientArgumentRequestBinder<Metadata> {
@Override
@NonNull
public Argument<Metadata> argumentType() {
return Argument.of(Metadata.class);
}
@Override
public void bind(@NonNull ArgumentConversionContext<Metadata> context,
@NonNull ClientRequestUriContext uriContext,
@NonNull Metadata value,
@NonNull MutableHttpRequest<?> request) {
request.header("X-Metadata-Version", value.getVersion().toString());
request.header("X-Metadata-Deployment-Id", value.getDeploymentId().toString());
}
}
Typed Argument Binder
import io.micronaut.core.annotation.NonNull
import io.micronaut.core.convert.ArgumentConversionContext
import io.micronaut.core.type.Argument
import io.micronaut.http.MutableHttpRequest
import io.micronaut.http.client.bind.ClientRequestUriContext
import io.micronaut.http.client.bind.TypedClientArgumentRequestBinder
import jakarta.inject.Singleton
@Singleton
class MetadataClientArgumentBinder implements TypedClientArgumentRequestBinder<Metadata> {
@Override
@NonNull
Argument<Metadata> argumentType() {
Argument.of(Metadata)
}
@Override
void bind(@NonNull ArgumentConversionContext<Metadata> context,
@NonNull ClientRequestUriContext uriContext,
@NonNull Metadata value,
@NonNull MutableHttpRequest<?> request) {
request.header("X-Metadata-Version", value.version.toString())
request.header("X-Metadata-Deployment-Id", value.deploymentId.toString())
}
}
Typed Argument Binder
import io.micronaut.core.convert.ArgumentConversionContext
import io.micronaut.core.type.Argument
import io.micronaut.http.MutableHttpRequest
import io.micronaut.http.client.bind.ClientRequestUriContext
import io.micronaut.http.client.bind.TypedClientArgumentRequestBinder
import jakarta.inject.Singleton
@Singleton
class MetadataClientArgumentBinder : TypedClientArgumentRequestBinder<Metadata> {
override fun argumentType(): Argument<Metadata> {
return Argument.of(Metadata::class.java)
}
override fun bind(
context: ArgumentConversionContext<Metadata>,
uriContext: ClientRequestUriContext,
value: Metadata,
request: MutableHttpRequest<*>
) {
request.header("X-Metadata-Version", value.version.toString())
request.header("X-Metadata-Deployment-Id", value.deploymentId.toString())
}
}
Binding On Method
It is also possible to create a binder, that would change the request with an annotation on the method. For example:
Client With Annotated Method
@Client("/")
public interface NameAuthorizedClient {
@Get("/client/authorized-resource")
@NameAuthorization(name="Bob") (1)
String get();
}
Client With Annotated Method
@Client("/")
public interface NameAuthorizedClient {
@Get("/client/authorized-resource")
@NameAuthorization(name="Bob") (1)
String get()
}
Client With Annotated Method
@Client("/")
public interface NameAuthorizedClient {
@Get("/client/authorized-resource")
@NameAuthorization(name="Bob") (1)
fun get(): String
}
1 | The @NameAuthorization is annotating a method |
The annotation is defined as:
Annotation Definition
@Documented
@Retention(RUNTIME)
@Target(METHOD) (1)
@Bindable
public @interface NameAuthorization {
@AliasFor(member = "name")
String value() default "";
@AliasFor(member = "value")
String name() default "";
}
Annotation Definition
@Documented
@Retention(RUNTIME)
@Target(METHOD) (1)
@Bindable
@interface NameAuthorization {
@AliasFor(member = "name")
String value() default ""
@AliasFor(member = "value")
String name() default ""
}
Annotation Definition
@MustBeDocumented
@Retention(RUNTIME)
@Target(FUNCTION) (1)
@Bindable
annotation class NameAuthorization(val name: String = "")
1 | It is defined to be used on methods |
The following binder specifies the behaviour:
Annotation Definition
@Singleton (1)
public class NameAuthorizationBinder implements AnnotatedClientRequestBinder<NameAuthorization> { (2)
@NotNull
@Override
public Class<NameAuthorization> getAnnotationType() {
return NameAuthorization.class;
}
@Override
public void bind( (3)
@NonNull MethodInvocationContext<Object, Object> context,
@NonNull ClientRequestUriContext uriContext,
@NonNull MutableHttpRequest<?> request
) {
context.getValue(NameAuthorization.class)
.ifPresent(name -> uriContext.addQueryParameter("name", String.valueOf(name)));
}
}
Annotation Definition
@Singleton (1)
public class NameAuthorizationBinder implements AnnotatedClientRequestBinder<NameAuthorization> { (2)
@NotNull
@Override
Class<NameAuthorization> getAnnotationType() {
return NameAuthorization.class
}
@Override
void bind( (3)
@NonNull MethodInvocationContext<Object, Object> context,
@NonNull ClientRequestUriContext uriContext,
@NonNull MutableHttpRequest<?> request
) {
context.getValue(NameAuthorization.class)
.ifPresent(name -> uriContext.addQueryParameter("name", String.valueOf(name)))
}
}
Annotation Definition
import io.micronaut.http.client.bind.AnnotatedClientRequestBinder
@Singleton (1)
class NameAuthorizationBinder: AnnotatedClientRequestBinder<NameAuthorization> { (2)
@NotNull
override fun getAnnotationType(): Class<NameAuthorization> {
return NameAuthorization::class.java
}
override fun bind( (3)
@NonNull context: MethodInvocationContext<Any, Any>,
@NonNull uriContext: ClientRequestUriContext,
@NonNull request: MutableHttpRequest<*>
) {
context.getValue(NameAuthorization::class.java, "name")
.ifPresent { name -> uriContext.addQueryParameter("name", name.toString()) }
}
}
1 | The @Singleton annotation registers it in Micronaut context |
2 | It implements the AnnotatedClientRequestBinder<NameAuthorization> |
3 | The custom bind method is used to implement the behaviour of the binder |