Brady Dowling
Brady Dowling

Reputation: 5562

Get API Gateway endpoints for Lambda function

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.

Upvotes: 0

Views: 2082

Answers (1)

Mark
Mark

Reputation: 92461

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

Upvotes: 2

Related Questions