要实现“AWS API网关发送响应并触发Lambda”的功能,您可以按照以下步骤操作:
import json
def lambda_handler(event, context):
# 处理API网关的请求
# ...
# 生成响应
response = {
"statusCode": 200,
"body": json.dumps({"message": "Hello, world!"}),
"headers": {
"Content-Type": "application/json"
}
}
return response
在AWS管理控制台中导航到“API网关”服务。
创建一个新的API或选择现有的API。
在API的资源中创建一个POST方法,并将其与Lambda函数关联。以下是一个示例的Python代码,用于将API网关的POST方法与Lambda函数关联:
import boto3
client = boto3.client('apigateway')
# 获取Lambda函数的ARN
lambda_arn = 'arn:aws:lambda:region:account-id:function:function-name'
# 获取API的ID
api_id = 'api-id'
# 获取资源的ID
resource_id = 'resource-id'
# 创建POST方法
response = client.put_method(
restApiId=api_id,
resourceId=resource_id,
httpMethod='POST',
authorizationType='NONE',
apiKeyRequired=False,
requestParameters={}
)
# 将POST方法与Lambda函数关联
response = client.put_integration(
restApiId=api_id,
resourceId=resource_id,
httpMethod='POST',
type='AWS',
integrationHttpMethod='POST',
uri=lambda_arn
)
# 配置Lambda函数的响应模板
response = client.put_integration_response(
restApiId=api_id,
resourceId=resource_id,
httpMethod='POST',
statusCode='200',
responseTemplates={
'application/json': ''
}
)
完成以上步骤后,API网关将在接收到来自客户端的POST请求时触发Lambda函数,并将Lambda函数的响应返回给客户端。