Daniel Minnaar Daniel Minnaar - 3 months ago 36
JSON Question

WSO2 - Transforming and aggregating different JSON data from multiple endpoints

I've created an API in WSO2 Carbon (5.0) which I POST a payload to:

{
"IdNumber" : "8008185218088",
"LastName" : null
}


I then call initiate a clone mediator sequence which forwards this payload to two different REST endpoints. The json response from the endpoints is different:

Endpoint 1 response:

{
"Name" : "Daniel",
"Number" : "12345678"
}


Endpoint 2 response:

{
"Name": "Bob",
"Address": "200 Bob Street",
"Code": "123"
}


The API response I'd like to create based on the above:

{
"Endpoint 1 Response" : {
"Name" : "Daniel",
"Number" : "12345678"
},

"Endpoint 2 Response" : {
"Name": "Bob",
"Address": "200 Bob Street",
"Code": "123"
}
}


What mediators on the
outSequence
do I need to configure to achieve this? How would I query the individual json response fields and combine them into a custom formatted json message for the client?

I've looked at the Aggregate mediator but I don't think it's right for differently formatted messages.

Here is my inSequence for reference:

<resource methods="POST">
<inSequence>
<property name="ROOT" scope="default">
<root:rootelement xmlns:root="www.wso2esb.com"/>
</property>
<log level="full"/>
<clone continueParent="true" id="test" sequential="true">
<target>
<sequence>
<send>
<endpoint>
<address uri="http://192.168.1.1/api/service/person" format="rest"/>
</endpoint>
</send>
</sequence>
</target>
<target>
<sequence>
<send>
<endpoint>
<address uri="http://192.168.1.1/api2/query" format="rest"/>
</endpoint>
</send>
</sequence>
</target>
</clone>
</inSequence>

Jan Jan
Answer

You will be unable to aggregate messages like this. A solution is to use the 'call' mediator, store the first response (or the values) in a property and call the second service afterwards.

Something like this:

<call>
   <endpoint>
       <address uri="http://192.168.1.1/api/service/person" format="rest"/>
   </endpoint>
</call>
<property name="Name1" expression="//Name" />
<property name="Number1" expression="//Number" />
<send>
   <endpoint>
       <address uri="http://192.168.1.1/api2/query" format="rest"/>
   </endpoint>
</send>
<outSequence>
-- build message using payloadfactory
</outSequence>

You can use a payloadFactory in the outSequence to build the response message.

Comments