Search code examples
micronaut

How do I pass dynamic header values to a Micronaut declarative HTTP client?


I would like to take advantage of the 'Declarative HTTP Client' feature of Micronaut. I am having a difficult time understand how to pass in a dynamic header value and was wondering if this is even possible. Consider the following example:

package com.example;

import io.micronaut.http.annotation.Header;
import io.micronaut.http.client.annotation.Client;
import java.util.ArrayList;

@Client("${my.api.host}")
@Header(name = "Auth-Header", value = "<This needs to be dynamic>")
public interface MyApiClient {
    public ArrayList<Dog> getDogs();
}

How can I make my header value dynamic [non-static]?


Solution

  • Dynamic headers in declarative client can be defined on the method argument level. See the example below:

    @Client("${my.api.host}")
    interface LocalhostClient {
        @Get
        List<String> getDogs(@Header(name = "Authorization") String authorization);
    }
    

    Then you can call the client method with appropriate Authorization header value like this:

    var dogs = client.getDogs("Bearer some-token");