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
- Click the “APIs” menu on the left pane
- Click the “Greeting” API
- 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
- Click the “Functions” menu on the left pane
- Click the “SayHello” function
- 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
- On the API page, click the “Stages” menu and select the $default Stage
- Copy the invoke URL and paste it into the browser.
- Attach the path “/greet/{your-name}” such as https://5k9ob4fp53.execute-api.us-east-1.amazonaws.com/greet/Tom
- Change the name part of the URL and see the response.
7. CouldWatch – Check the Lambda logs
- On the Lambda function page, click the “Monitor” tab
- Check some metrics on the page
- Click the “View logs in the CloudWatch” button
- On the CloudWatch page, click the “Log stream“
- Check the logs