Toli
Toli

Reputation: 5777

In AWS API Gateway, How do I include a stage parameter as part of the event variable in Lambda (Node)?

I have a stage variable set up called "environment".

I would like to pass it through in a POST request as part of the JSON.

Example:

Stage Variables

JSON

{
  "name": "Toli",
  "company": "SomeCompany"
}

event variable should look like;

{
  "name": "Toli",
  "company": "SomeCompany",
  "environment": "development"
}

So far the best I could come up with was the following mapping template (under Integration Request):

{
    "body" : $input.json('$'),
    "environment" : "$stageVariables.environment"
}

Then in node I do

exports.handler = function(event, context) {
    var environment = event.environment;
    // hack to merge stage and JSON
    event = _.extend(event.body, {
      environment : environment
    });
    ....

Upvotes: 2

Views: 1667

Answers (3)

Maxime Rainville
Maxime Rainville

Reputation: 2049

If your API Gateway method use Lambda Proxy integration, all your stage variables will be available via the event.stageVariables object.

For the project I'm currently working on, I created a simple function that goes over all the properties in event.stageVariables and appends them to process.env (e.g.: Object.assign(process.env, event.stageVariables);)

Upvotes: 5

Alex
Alex

Reputation: 892

You can also access the stage name in the $context object.

Integration Request:

{
    "environment" : "$context.stage"
}

Upvotes: 0

Bob Kinney
Bob Kinney

Reputation: 9020

Your suggestion of using a mapping template to pass-through the variable would be the recommended solution for this type of workflow.

Upvotes: 1

Related Questions