Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท HTTP Server and Clients

Declarative HTTP Clients

Call other services in Micronaut by writing an interface with @Client and @Get. Learn URI templates, error handling, and see the idea in a runnable Java stand-in.

Most services call other services. In many frameworks that means building a request, sending it, checking the status, and parsing the body, over and over. Micronaut lets you write only the contract. You declare an interface, annotate the methods with the HTTP verb and path, and the framework generates the implementation at compile time. This is the declarative HTTP client.

The framework code below is read-only because Micronaut is not installed on this site. The runnable programs are Java stand-ins: a dynamic proxy that turns an annotated interface into requests (the same trick, built with reflection instead of compile-time generation), and a URI template expander. Both run against an in-memory fake transport, so no network is needed.

Your first client

Java
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.client.annotation.Client;

@Client("https://api.example.com/v1")
public interface BookClient {

    @Get("/books/{id}")
    Book find(long id);

    @Get("/books{?author,page}")
    List<Book> list(@Nullable String author, @Nullable Integer page);

    @Post("/books")
    Book create(@Body NewBook book);
}

Inject it like any bean and call it as if it were a local object:

Java
@Singleton
public class CatalogService {
    private final BookClient books;

    public CatalogService(BookClient books) { this.books = books; }

    public String title(long id) { return books.find(id).title(); }
}

Micronaut builds the URL from the base path in @Client, plus the route in @Get. Path variables in braces are filled from the method parameters with the same name. The {?author,page} form is a URI template for optional query parameters: a null value is simply left out. The response body is parsed into the return type with the same serialization used by the server (see JSON and serialization).

Return types decide the style

The return type tells Micronaut how you want the call to behave:

Return type Behavior
Book Blocking. Waits for the response and returns the body
Optional<Book> Blocking; a 404 becomes Optional.empty()
HttpResponse<Book> Blocking; gives you status and headers too
Publisher<Book>, Mono<Book> Reactive; nothing is sent until someone subscribes
CompletableFuture<Book> Asynchronous; returns immediately

Use the blocking forms only on threads that may block. On a Netty event-loop thread a blocking client call can stall the server, so reactive types are safer there. Controllers that run on the blocking executor (@ExecuteOn(TaskExecutors.BLOCKING)) can use the simple forms.

Headers, authentication and configuration

Java
@Client(id = "inventory")
@Header(name = "Accept", value = "application/json")
public interface InventoryClient {

    @Get("/stock/{sku}")
    StockLevel stock(String sku, @Header("X-Request-Id") String requestId);

    @Get("/secure/report")
    String report(@Header("Authorization") String bearer);
}

With @Client(id = "inventory") the base URL comes from configuration, so you can change it per environment without touching code:

YAML
micronaut:
  http:
    services:
      inventory:
        url: "https://inventory.internal:8443"
        read-timeout: 5s
        pool:
          enabled: true

You can also add a @Header at the interface level (sent on every call), set @Client(path = "/v2") for a shared prefix, and tune timeouts, connection pools, proxy settings and TLS for each named service. If service discovery is set up, the id can name a service that is resolved at call time (see service discovery).

Errors

A 4xx or 5xx response makes a blocking client throw HttpClientResponseException, which carries the status and, if present, the parsed error body:

Java
try {
    return books.find(id);
} catch (HttpClientResponseException e) {
    if (e.getStatus() == HttpStatus.NOT_FOUND) {
        return Book.unknown();
    }
    throw e;
}

For an Optional return, 404 is not an exception. Network problems (refused connection, timeout) raise HttpClientException subclasses such as ReadTimeoutException. Combine the client with @Retryable and @CircuitBreaker when the remote service is flaky: place the annotations directly on the client interface methods.

You can also write the client as an abstract class, or as an interface with default methods, when you need custom logic around the generated calls. For full manual control, inject the low-level HttpClient and build the request yourself:

Java
HttpRequest<?> request = HttpRequest.GET("/books/7").header("Accept", "application/json");
HttpResponse<Book> response = httpClient.toBlocking().exchange(request, Book.class);

Declarative client flow

Interface You write the contract.
Build time Micronaut generates the code.
Call Method call becomes an HTTP request.
Result Body is parsed into your type.

Less boilerplate, same control when you need it.

1 / 2

Stand-in 1: an annotated interface becomes requests

The program below defines its own tiny annotations (@Get, @Post) and uses java.lang.reflect.Proxy to turn an interface into a client. A fake transport plays the server and returns canned text, so the output is always the same. It is not the Micronaut implementation, but the mapping from a method call to an HTTP request is the same idea.

Java Interface in, HTTP request out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The custom @P annotation names each parameter, because plain Java does not keep parameter names at run time unless you compile with -parameters. Micronaut does not need such a marker: its annotation processor reads the parameter names at compile time.

Stand-in 2: expanding URI templates

Path variables use and optional query values use {?a,b}. This expander implements the two forms and leaves out null values, which is the rule Micronaut follows for optional query parameters.

Java A small URI template expander

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice how encoding protects you: the space in Ursula Le Guin becomes %20, so user input cannot break out of its URL segment.

Practical advice

  • Keep clients thin. One client interface per remote service; put mapping and business rules in a service bean.
  • Use separate DTO records for the remote contract. Do not reuse your database entities.
  • Set timeouts per service. The defaults are generous, and one slow dependency can exhaust your threads.
  • Do not log secrets. Authorization headers can show up in verbose HTTP logging.
  • Test with a fake server. The test chapter shows how to replace a client with a mock bean or a local test server; see mocking and test resources.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Micronaut do with an interface annotated with @Client?

    Micronaut's annotation processor creates the client implementation during compilation, so you only write the contract.
  2. 2. A blocking client method returns Optional<Book>. What happens on a 404 response?

    For Optional return types, a 404 is treated as an absent value rather than an error.
  3. 3. How is a null parameter handled in a URI template such as /books{?author,page}?

    Optional query parameters with null values are omitted, so the URL stays clean.
  4. 4. Why should you avoid blocking client calls on event-loop threads?

    A blocked event-loop thread cannot serve other connections. Use reactive types or the blocking executor.

Summary

  • A declarative client is an interface with @Client and verb annotations; Micronaut generates the implementation at compile time.
  • Path variables and {?query} templates are filled from parameters, and null query values are omitted.
  • The return type chooses blocking, Optional, HttpResponse, reactive or future-based behavior.
  • @Client(id = ...) reads URL, timeouts and pooling from configuration.
  • Blocking calls throw HttpClientResponseException on 4xx and 5xx responses.
  • Combine clients with retry and circuit-breaker advice for flaky dependencies.

Next: Filters and Error Handling