The best way to join an API Gateway to Lambda in CloudFormation


To attach an API Gateway to a Lambda operate utilizing CloudFormation, you may observe these steps:

  1. Outline your API Gateway and Lambda operate sources in your CloudFormation template. Right here’s an instance:
Assets:
  MyLambdaFunction:
    Sort: AWS::Lambda::Operate
    Properties:
      FunctionName: MyLambdaFunction
      Runtime: python3.8
      Handler: index.handler
      Code:
        S3Bucket: my-lambda-code-bucket
        S3Key: lambda-code.zip

  MyApiGateway:
    Sort: AWS::ApiGateway::RestApi
    Properties:
      Title: MyApiGateway
  1. Create a useful resource of kind AWS::ApiGateway::Useful resource to outline the useful resource path on your API Gateway:
  MyApiGatewayResource:
    Sort: AWS::ApiGateway::Useful resource
    Properties:
      RestApiId: !Ref MyApiGateway
      ParentId: !GetAtt MyApiGateway.RootResourceId
      PathPart: myresource
  1. Create a way on the useful resource to outline the HTTP technique (e.g., GET, POST) and integration particulars:
  MyApiGatewayMethod:
    Sort: AWS::ApiGateway::Technique
    Properties:
      RestApiId: !Ref MyApiGateway
      ResourceId: !Ref MyApiGatewayResource
      HttpMethod: GET
      AuthorizationType: NONE
      Integration:
        Sort: AWS
        IntegrationHttpMethod: POST
        Uri: !Sub arn:aws:apigateway:${AWS::Area}:lambda:path/2015-03-31/capabilities/${MyLambdaFunction.Arn}/invocations

Within the above instance, the Uri property references the ARN of the Lambda operate.

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

The SourceArn property references the ARN of your API Gateway.

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

These steps will create an API Gateway that’s related to your Lambda operate. Requests made to the API Gateway endpoint might be routed to your Lambda operate for processing.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles