API Gateway to Inline Lambda in CloudFormation


To connect an API Gateway to an inline 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:
  MyApiGateway:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: MyApiGateway

  MyApiGatewayResource:
    Type: AWS::ApiGateway::Resource
    Properties:
      RestApiId: !Ref MyApiGateway
      ParentId: !GetAtt MyApiGateway.RootResourceId
      PathPart: myresource

  MyApiGatewayMethod:
    Type: AWS::ApiGateway::Method
    Properties:
      RestApiId: !Ref MyApiGateway
      ResourceId: !Ref MyApiGatewayResource
      HttpMethod: GET
      AuthorizationType: NONE
      Integration:
        Type: AWS_PROXY
        IntegrationHttpMethod: POST
        Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:MyLambdaFunction/invocations"

  MyApiGatewayDeployment:
    Type: AWS::ApiGateway::Deployment
    Properties:
      RestApiId: !Ref MyApiGateway

  MyApiGatewayStage:
    Type: AWS::ApiGateway::Stage
    Properties:
      StageName: prod
      RestApiId: !Ref MyApiGateway
      DeploymentId: !Ref MyApiGatewayDeployment

  MyLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: MyLambdaFunction
      Runtime: python3.8
      Handler: index.lambda_handler
      Code:
        ZipFile: |
          def lambda_handler(event, context):
              return {
                  'statusCode': 200,
                  'body': 'Hello from Lambda!'
              }          

In the above example, the Lambda function is defined inline using the ZipFile property. The code inside the lambda_handler function can be customized according to your requirements.

  1. Add the necessary permission for API Gateway to invoke the Lambda function:
  MyLambdaPermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !GetAtt MyLambdaFunction.Arn
      Action: lambda:InvokeFunction
      Principal: apigateway.amazonaws.com
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MyApiGateway}/*/*/*"
  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 inline Lambda function. Requests made to the API Gateway endpoint will be routed to your Lambda function for processing.