0

I have a Lambda function that has an API Gateway trigger. I'd like to programmatically get which API it is and what the resource path is. Here is some of the code I have so far.

let params = { FunctionName: "myFunctionName" }; // Get policies for this function lambda.getPolicy(params, (err, data) => { if (err) return console.log(err); let apiIds = []; let statements = JSON.parse(data.Policy).Statement; // Look for ARNs that have an API ID attached to them statements.forEach((statement) => { let sourceArn = statement.Condition && statement.Condition.ArnLike && statement.Condition.ArnLike["AWS:SourceArn"]; let apiIdMatch = sourceArn.match(/\d{12}:([0-9a-zA-Z]*)\//); let apiId = apiIdMatch[1]; if (statement.Effect === "Allow") { // Probably need to be more selective here // Check if this resource is actually an API or if it's something else apigateway.getRestApi({ restApiId: apiId }, (err, data) => { if (err) return; // Not a real API, look for another // This is a real API? I think I still need the endpoint/resource path }); } }); }); 

Seems like there should be an easier way than this so I'm wondering if I'm even taking the right approach.

Note: For context, I'm looking for a way of testing the API endpoints that are attached as triggers for my Lambda function, so getting the resource path from the event is not an option. Furthermore, I'm looking for a way of doing this without any extra mapping or configuration.

1 Answer 1

2

If you are using Lambda proxy integration, The API Gateway passes this stuff to your lambda function in:

 event.requestContext.resourcePath event.requestContext.apiId 

i.e

exports.handler = function(event, context, callback){ var path = event.requestContext.resourcePath, var apiId = event.requestContext.apiId //... } 

If you are not using proxy integration you can setup an integration mapping in the API Gateway console for application/json with something like this in the mapping template:

{"resourcePath" : "$context.resourcePath", "apiId": "$context.apiId" } 

Then event.resourcePath and event.apiId should be available to your function

Sign up to request clarification or add additional context in comments.

1 Comment

This is true, I suppose I should have added more context. I'm looking for a way of testing the API endpoints that are triggers for my lambda function, so the first suggestion you mentioned (getting the resource path from the event) doesn't apply here (though that's helpful for the future) and the second suggestion is good but I'm looking for a way of doing this without any extra mapping or configuration i.e. a method anyone could use out of the box.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.