What is the easiest way of adding objects augment/enrich a incoming payload

apiguru
Participant II

Hi,

What is the easiest and best of enriching a incoming payload to target endpoint.

Example:

Incoming Request

{
"firstName":"ABC",
"lastName":"DEF"
}

Outgoing Request:

{
  "firstName": "ABC",
  "lastName": "DEF",
  "someArray": [
    {
      "key1": "value1",
      "key2": "value2"
    }
  ]
}
1 3 341
3 REPLIES 3

Well there are two things to consider.

  1. mechanics: how would you inject properties into a JSON payload
  2. data model: where is the data store that you inject into the JSON payload

The answer to the first question is really easy: use a JavaScript callout, it's really simple and it will work nicely for you.

<Javascript name='JS-1' timeLimit='200' >
  <Source>
    var c = JSON.parse(context.getVariable('request.content'));
    c.someArray = [ item1, item2 ];
    context.setVariable('request.content', JSON.stringify(c));
  </Source>
</Javascript>

The second question is more interesting. Where does the data come from? The common patterns here are to store the data as a custom attribute on the API Product, or on the Developer App. A derivative pattern is to store the additional data "indirectly": store it in the KeyValueMap in Apigee, using the clientid, or the productid, or the developerid as the key.

Regardless whether you store the value directly as a custom attribute on the app or product or developer, or indirectly using the KVM, you would then have the JSON in a context variable (as a string). So in the JS that augments the payload you'd JSON.parse() that context variable, and then append the result of that into the JS object. Something like this:

<Javascript name='JS-1' timeLimit='200' >
  <Source>
    var c = JSON.parse(context.getVariable('request.content'));
    var augmentation = JSON.parse(context.getVariable('other_variable'));
    c.someArray = augmentation
    context.setVariable('request.content', JSON.stringify(c));
  </Source>
</Javascript>

Helpful?

@Dino-at-Google

to answer your second question, the data would come from a intermediate call aka Call an external party for additional required properties.

Ahh, ok! That's a scenario I hadn't covered there. But anyway, same idea applies. You'd just use a different context variable.