7
votes

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!

1
It sounds like this should be part of the build/deploy process? So during deploy on your build server you call the vendor API and receives the URL and you then use that to set a env variable? Or can you elaborate on the flow you want to support.doorstuck
The problem is that the hosts get provisioned when the stack is deployed, so its a chicken and egg problem. I can't pass them as env variable because it don't exist yet.DLeonardi

1 Answers

10
votes

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.