Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing serverless API Gateway URL as a parameter for a Lambda function in the same stack

I started building a JAM app using AWS Lambda, AWS API Gateway and serverless, as well as another vendors API.

This vendor API is invoked by a Lambda function, and requires a callback URL to be passed to receive some data once it has done its job.

As I'm spawning everything with serverless, going to the console and extracting the API URL to manually set is as an env variable is of no use to me, and I need a way so that serverless can pass the exposed API endpoint URL to the lambda function.

How do I get the Lambda function HTTP event URI as an env or something passable to another Lambda function in the same stack?

Can someone provide some serverless snippet on how to achieve this? Thanks!

like image 928
duck degen Avatar asked Feb 01 '17 07:02

duck degen


1 Answers

If you want to find the API Gateway URL that triggered the Lambda function, you need to check the event variable that your Lambda function receives.

event.headers.Host -> abcdefghij.execute-api.us-east-1.amazonaws.com
event.requestContext.stage -> dev
event.requestContext.resourcePath -> my-service/resource

If you want to build the API Gateway URL (example: https://abcdefghij.execute-api.us-east-1.amazonaws.com/dev/my-service/resource), use:

const url = `https://${event.headers.Host}/${event.requestContext.stage}/${event.requestContext.resourcePath}`;

Complete test example:

module.exports.hello = (event, context, callback) => {

  const url = `https://${event.headers.Host}/${event.requestContext.stage}/${event.requestContext.resourcePath}`;

  const response = {
    statusCode: 200,  
    headers: {
      'Access-Control-Allow-Origin': '*'
    },  
    body: JSON.stringify({
        message: url
    })
  };

  callback(null, response);
};

Note: if you test this directly in the AWS Lambda Console, it may throw an error because the event object will be empty and without the headers and requestContext properties. So, try this using the API Gateway console or browsing the URL directly.

like image 143
Zanon Avatar answered Oct 06 '22 16:10

Zanon