[AWS Lab] Synchronous Lambda Invocation – API Gateway

In this lab, we will learn how to invoke a lambda function synchronously.

  • Overview
  • Source: API Gateway – HTTP API
    • Route: GET /greet/{name}
  • Target: Lambda – Function
    • Returns the greeting message
    • Python

1. Lambda – Create a Function

  • Function Name: “SayHello
  • Runtime: Python 3.9

2. Lambda Function Code – Python

  • Type the following code
  • Click “Deploy
import json
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    name = event['pathParameters']['name']
    logger.info(event)
 
    response = {
        'statusCode': 200,
        'headers': {
          'Content-Type': 'text/html',
        },
        'body': '<html><h2>Here is the greeting</h2><hr /><p>Hello '+ name + '!</p></html>',
    }
    return response

3. API Gateway – Create the API HTTP API

  • HTTP API -> Click “Build
  • Configuration
    • Name: “Greeting
    • Add Integration: Lambda – “SayHello
  • Routes
    • GET – “/greet/{name}
  • Stages
    • $default + Enable Auto Deploy

4. API – Check the Invoke Permissions

  1. Click the “APIs” menu on the left pane
  2. Click the “Greeting” API
  3. Click the “Integrations” menu on the left pane
    • Click the “GET” link under the “/greet/{name}” route
    • Find the “Invoke” permissions and expand the “Policy statement

5. Lambda – Check the Resource-based policy

  1. Click the “Functions” menu on the left pane
  2. Click the “SayHello” function
  3. Check Configuration -> Permissions -> Resource-based policy statements -> View policy
    • Confirm that the API can call the Lambda
{
  "Version": "2012-10-17",
  "Id": "default",
  "Statement": [
    {      
      "Effect": "Allow",
      "Principal": {
        "Service": "apigateway.amazonaws.com"
      },
      "Action": "lambda:InvokeFunction",
      "Resource": "arn:aws:lambda:{region}:{account}:function:{function-name}",
      "Condition": {
        "ArnLike": {
          "AWS:SourceArn": "arn:aws:execute-api:{region}:{account}:{api-id}/*/*/{route-name}"
        }
      }
    }
  ]
}

6. Test the endpoint – API

  1. On the API page, click the “Stages” menu and select the $default Stage
  2. Copy the invoke URL and paste it into the browser.
  3. Change the name part of the URL and see the response.

7. CouldWatch – Check the Lambda logs

  1. On the Lambda function page, click the “Monitor” tab
  2. Check some metrics on the page
  3. Click the “View logs in the CloudWatch” button
  4. On the CloudWatch page, click the “Log stream
  5. Check the logs

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s