Skip to content
Advertisement

Merge two api responses into one using Webclient – Webflux

I’m using WebFlux and WebClient and I need to consume two APIs and merge its responses.

The first API receive type and document number and returns a list with one element that contains customer data (that’s how it’s defined).

The second API receive a client id and returns a customer payments list.

I need to consume these two APIs and return an entity with the customer data and their payments.

API Customer response

JavaScript
JavaScript

API Payment Response

JavaScript

finally I should have this

CustomerResponse.java

JavaScript

I have a proxy class that is responsible for making the API call

CustomerProxy.java

JavaScript

PaymentProxy.java

JavaScript

And a service that is responsible for merge responses CustomerServiceImpl.java

JavaScript

What should I do? enter image description here

Advertisement

Answer

Two ways to resolve this:

  1. Using nested maps:
JavaScript
  1. Using zip: Since you need info from the response of first API in your second API, you need to chain these two together. Now since they are async calls, you need a flatMap or a variant of flatMap called flatMapMany which emits more than one elements (which exactly what your 2nd API is doing). Next, you need both the responses to build your CustomerResponse i.e you need to zip the two reactive stream responses from the two APIs.

Thus basically using Method2 you need this:

JavaScript

Demerit of Method2: Api1 i.e customer API will be be subscribed twice.

Advertisement