Labels

Friday, July 22, 2016

Transforming a Json Request In WSO2 API Cloud

Hi All,

If you require to transform an incoming Json request to a Json request  of a different format (Add extra values). You can simply do it by changing the default mediation flow.
This post is to show how you could archive that in a simple and easy steps.

Payload sent from user to the backend

  "tutorials": {
        "id": "wso2",
        "topic": "REST Service",
        "description": "This is REST Service Example by WSO2."
    }


Modified payload sent to backend - (Add the username of the user to the payload data )

{
  "data": {
    "tutorials": {
      "id": "wso2",
      "topic": "REST Service",
      "description": "This is REST Service Example by WSO2."
    }
  },
  "user": "vinurid.wso2.com@testuser"
}


All you have to do is write a custom sequence that modify the payload using PayloadFactory Mediator.
If you want to know more details about the mediator can follow this WSO2 Documentation - https://docs.wso2.com/display/ESB490/PayloadFactory+Mediator

This is a sample sequence that you can use to do the above Payload transformation. You have to save the bellow sequence to an xml file and add to the in-sequence in the API.

<sequence xmlns="http://ws.apache.org/ns/synapse" name="CustomerSequence">
         <payloadFactory media-type="json">
            <format>{"data":$1, "user":"$2"}</format>
            <args>
               <arg evaluator="json" expression="json-eval($)"/>
            <arg expression="$ctx:api.ut.userId"/>
            </args>
         </payloadFactory>
</sequence>


You could follow the bellow video on step by step guidance on how to do this in WSO2 Cloud.
Content in the video
1. Creating an API in WSO2 Cloud.
2. Change the mediation flow in the API in-sequence
3. Show the sequence that added to the in-sequence
4. publish the API
5. Subscribe to the newly created API in WSO2 API Cloud
6. Invoke the API. (Video shows the payload which user sent to the backend)
7. Shows the output for the request
8. Shows the in-coming request in the backend logs. (Request that sent to the backend from the WSO2 API Cloud)




No comments:

Post a Comment