Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To call an external service (API) correctly in a reactive Quarkus application using Vertx and Mutiny, use the following steps:

  1. Obtain the Mutiny.Vertx instance:
Mutiny.Vertx vertx = Mutiny.Vertx.vertx();
  1. Create a WebClient instance using the Vertx instance:
WebClient webClient = WebClient.create(vertx);
  1. Define the HTTP request to the external service using the WebClient instance:
Uni<HttpResponse<Buffer>> response = webClient.get(8080, "external-service.com", "/api/resource")
    .addQueryParam("param", "value")
    .send();
  1. Extract the response from the Uni instance using the onItem method:
response.onItem().transform(resp -> parseResponse(resp.bodyAsString())).subscribe().with(result -> {
    // Process the response
});
  1. Parse the response using the appropriate method, such as JsonObject.mapFrom or Json.decodeValue.

  2. Use appropriate error handling techniques such as using .onFailure().retry().atMost(3) to retry the HTTP request a few times if it fails.

Example code:

public Uni<MyResponse> callExternalService() {
    Mutiny.Vertx vertx = Mutiny.Vertx.vertx();
    WebClient webClient = WebClient.create(vertx);

    Uni<HttpResponse<Buffer>> response = webClient.get(8080, "external-service.com", "/api/resource")
        .addQueryParam("param", "value")
        .send();

    return response.onItem().transform(resp -> parseResponse(resp.bodyAsString()))
        .onFailure().retry().atMost(3);
}

private MyResponse parseResponse(String responseJson) {
    JsonObject responseObj = JsonObject.mapFrom(responseJson);
    // ...
    return myResponse;
}