How to Connect an API Gateway to Lambda in CloudFormation

To connect an API Gateway to a Lambda function using CloudFormation, you can follow these steps:

  1. Define your API Gateway and Lambda function resources in your CloudFormation template. Here’s an example:
Resources:
  MyLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: MyLambdaFunction
      Runtime: python3.8
      Handler: index.handler
      Code:
        S3Bucket: my-lambda-code-bucket
        S3Key: lambda-code.zip

  MyApiGateway:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: MyApiGateway
  1. Create a resource of type AWS::ApiGateway::Resource to define the resource path for your API Gateway:
  MyApiGatewayResource:
    Type: AWS::ApiGateway::Resource
    Properties:
      RestApiId: !Ref MyApiGateway
      ParentId: !GetAtt MyApiGateway.RootResourceId
      PathPart: myresource
  1. Create a method on the resource to define the HTTP method (e.g., GET, POST) and integration details:
  MyApiGatewayMethod:
    Type: AWS::ApiGateway::Method
    Properties:
      RestApiId: !Ref MyApiGateway
      ResourceId: !Ref MyApiGatewayResource
      HttpMethod: GET
      AuthorizationType: NONE
      Integration:
        Type: AWS
        IntegrationHttpMethod: POST
        Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations

In the above example, the Uri property references the ARN of the Lambda function.

  1. Add a permission for API Gateway to invoke your Lambda function:
  MyLambdaPermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref MyLambdaFunction
      Action: lambda:InvokeFunction
      Principal: apigateway.amazonaws.com
      SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MyApiGateway}/*/*/*

The SourceArn property references the ARN of your API Gateway.

  1. Deploy your API Gateway:
  MyApiGatewayDeployment:
    Type: AWS::ApiGateway::Deployment
    Properties:
      RestApiId: !Ref MyApiGateway
  1. Associate the deployment with a stage (e.g., “prod”):
  MyApiGatewayStage:
    Type: AWS::ApiGateway::Stage
    Properties:
      StageName: prod
      RestApiId: !Ref MyApiGateway
      DeploymentId: !Ref MyApiGatewayDeployment
  1. After defining these resources, you can deploy your CloudFormation stack using the AWS CloudFormation service or the AWS CLI.

These steps will create an API Gateway that is connected to your Lambda function. Requests made to the API Gateway endpoint will be routed to your Lambda function for processing.