0
0
AWScloud~5 mins

Lambda integration in AWS - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want your cloud app to run code automatically when something happens, like a file upload or a web request. AWS Lambda lets you run small pieces of code without managing servers. Lambda integration means connecting Lambda to other AWS services so your code runs at the right time.
When you want to run code automatically after a user uploads a file to storage.
When you want to process data as soon as it arrives in a database.
When you want to respond to web requests without managing servers.
When you want to automate tasks triggered by changes in your cloud environment.
When you want to connect your code to events from other AWS services easily.
Config File - lambda-integration.yaml
lambda-integration.yaml
Resources:
  MyLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: example-lambda
      Runtime: python3.9
      Handler: index.handler
      Role: arn:aws:iam::123456789012:role/lambda-execution-role
      Code:
        ZipFile: |
          def handler(event, context):
              print("Hello from Lambda")
              return {'statusCode': 200, 'body': 'Hello World'}

  MyApiGateway:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: example-api

  MyApiResource:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId: !GetAtt MyApiGateway.RootResourceId
      PathPart: hello
      RestApiId: !Ref MyApiGateway

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

  LambdaPermission:
    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}/*/GET/hello

This YAML file creates a Lambda function that runs Python code printing a message and returning a response.

It sets up an API Gateway REST API with a resource path '/hello' and a GET method.

The GET method is integrated with the Lambda function using AWS_PROXY, which means the API Gateway forwards requests directly to Lambda.

LambdaPermission allows API Gateway to invoke the Lambda function securely.

Commands
This command deploys the CloudFormation stack that creates the Lambda function, API Gateway, and permissions. It sets up the integration automatically.
Terminal
aws cloudformation deploy --template-file lambda-integration.yaml --stack-name example-lambda-stack --capabilities CAPABILITY_NAMED_IAM
Expected OutputExpected
Waiting for stack create/update to complete... Successfully created/updated stack - example-lambda-stack
--template-file - Specifies the CloudFormation template file to deploy
--stack-name - Names the CloudFormation stack
--capabilities - Allows creation of IAM roles needed by Lambda
This command lists the API Gateway REST APIs to find the API ID needed to call the endpoint.
Terminal
aws apigateway get-rest-apis
Expected OutputExpected
{ "items": [ { "id": "a1b2c3d4e5", "name": "example-api", "description": "" } ] }
This command calls the API Gateway endpoint that triggers the Lambda function, showing the Lambda response.
Terminal
curl https://a1b2c3d4e5.execute-api.us-east-1.amazonaws.com/prod/hello
Expected OutputExpected
{"statusCode":200,"body":"Hello World"}
Key Concept

If you remember nothing else from this pattern, remember: Lambda integration lets you run code automatically in response to events from other AWS services without managing servers.

Common Mistakes
Not granting API Gateway permission to invoke the Lambda function.
API Gateway cannot call Lambda without explicit permission, causing errors when invoking the function.
Add a Lambda permission resource allowing API Gateway to invoke the function, specifying the correct source ARN.
Using the wrong URI format for Lambda integration in API Gateway.
API Gateway will fail to connect to Lambda if the URI is incorrect, causing 502 errors.
Use the correct URI format: arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/{function_arn}/invocations
Not deploying the API stage before calling the endpoint.
The API endpoint won't be available until the API is deployed, causing 404 errors.
Deploy the API stage (e.g., 'prod') in API Gateway before testing the endpoint.
Summary
Create a Lambda function and an API Gateway REST API with a resource and method.
Integrate the API Gateway method with the Lambda function using AWS_PROXY integration.
Grant API Gateway permission to invoke the Lambda function.
Deploy the CloudFormation stack to set up all resources.
Call the API Gateway endpoint to trigger the Lambda function and get the response.