Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a key/value pair to an object in VTL (for API Gateway)

I am writing a mapping template for an AWS API Gateway integration response. I would like to add a key/value pair to the JSON object returned my Lambda function.

My function returns some JSON like this:

{
  "id": "1234",
  "name": "Foo Barstein"
}

I would like the template to output something like this:

{
  "id": "1234",
  "name": "Foo Barstein",
  "href": "https://example.tld/thingy/1234"
}

And my mapping template looks like this:

#set($thingy = $input.json('$'))
#set($thingy.href = "https://example.tld/thingy/$thingy.id")

$thingy

However, my template outputs the unmodified $thingy, without the href I have tried to add.

I've read the VTL user guide, but to no avail.

like image 844
Josh Glover Avatar asked Dec 07 '17 10:12

Josh Glover


2 Answers

Something like this has worked for me:

#set($body = $input.path('$'))
#set($body.href = "https://example.tld/thingy/$body.id")
$input.json('$')
like image 130
Pablo López Martínez Avatar answered Oct 19 '22 08:10

Pablo López Martínez


There is no easy way to achieve this but you can workaround it:

## Mapping template
#set($body = $input.body)
#set($id = $input.json('$.id'))
{
  "custom": {
    "href" : "https://example.tld/thingy/$id"
  },
  "body": $body
}

And then merge all the keys in AWS.Lambda (if you use Lambda):

## Lambda handler
exports.handler = function(event, context) {
  const requestParams = Object.assign({}, event.body, event.custom);
  // ... function code
}

And requestParams will be what you want.

like image 2
D.Dimitrioglo Avatar answered Oct 19 '22 09:10

D.Dimitrioglo