Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To grant authorization for API Gateway to call a Lambda function within a CloudFormation template, follow these steps:

  1. In your CloudFormation template, define your API Gateway and Lambda function resources.

  2. Add a resource policy to your Lambda function, which will allow the API Gateway to invoke it. For example:

"MyFunction": {
    "Type": "AWS::Lambda::Function",
    "Properties": {
        "FunctionName": "my-function",
        "Code": {...},
        "Role": {...},
        "Handler": "...",
        "Runtime": "nodejs14.x",
        "ResourcePolicy": {
            "PolicyDocument": {
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": {
                            "Service": [
                                "apigateway.amazonaws.com"
                            ]
                        },
                        "Action": "lambda:InvokeFunction",
                        "Resource": "*"
                    }
                ]
            }
        }
    }
}
  1. Add an integration between your API Gateway and Lambda function, specifying the ARN of the Lambda function and the method for invoking it. For example:
"MyRestApi": {
    "Type": "AWS::ApiGateway::RestApi",
    "Properties": {
        "Name": "my-api"
    }
},
"MyResource": {
    "Type": "AWS::ApiGateway::Resource",
    "Properties": {
        "ParentId": {"Fn::GetAtt": ["MyRestApi", "RootResourceId"]},
        "PathPart": "my-resource"
    }
},
"MyMethod": {
    "Type": "AWS::ApiGateway::Method",
    "Properties": {
        "RestApiId": {"Ref": "MyRestApi"},
        "ResourceId": {"Ref": "MyResource"},
        "HttpMethod": "GET",
        "AuthorizationType": "NONE",
        "Integration": {
            "IntegrationHttpMethod": "POST",
            "Type": "AWS_PROXY",
            "Uri": {"Fn::Join": ["", ["arn:aws:apigateway:", {"Ref": "AWS::Region"}, ":lambda:path/2015-03-31/functions/", {"Fn::GetAtt": ["MyFunction", "Arn"]}, "/invocations"]]}
        }
    }
}
  1. Deploy your API Gateway, which will create an endpoint for invoking your Lambda function.

With these steps, your API Gateway will be authorized to call your Lambda function, and your CloudFormation stack will be able to create and manage the resources needed for this integration.