首页 > 解决方案 > 如何使用 API 网关将参数传递给 Lambda 函数以从 DynamoDB 中查询项目?

问题描述

我有一个 Lambda 函数来从 DynamoDB 表中查询数据。Lambda函数如下:

'use strict';

var AWS = require('aws-sdk'),
documentClient = new AWS.DynamoDB.DocumentClient(); 

exports.listItems = function(event, context, callback){
var params = {
TableName : event.tablename,
IndexName : "active_flag-index",
KeyConditionExpression: "#active = :active",
FilterExpression: "#deliverable = :deliverable and #type = :type",
ProjectionExpression: "#name, price, item_description, item_type",
ExpressionAttributeNames:{
    "#active": "active_flag",
    "#deliverable": "deliverable_flag",
    "#name": "name",
    "#type": "item_type"
},
ExpressionAttributeValues: {
    ":active": "active",
    ":deliverable": "deliverable",
    ":type": event.type
}
};
documentClient.query(params, function(err, data) {
if (err) {
    console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
    console.log("Query succeeded.");
    data.Items.forEach(function(item) {
        console.log(" -", item.name + ": " + item.price);
    });
}
});
}

测试参数为 { "tablename": "vijayarams_items", "type": "Main Dish" } 使用此测试参数,成功检索到 Main Dish 对应的项目。现在,我不确定如何使用 API 传递这些参数来调用这个 Lambda 函数。我用 GET 方法创建了一个 API,但 GET 方法不使用请求正文来发送参数。请告诉我如何进一步进行。我能够创建表,使用 AJAX 的 POST 方法更新项目并将参数传递给正文。我只是无法使用设置的参数从表中查询项目。

标签: amazon-web-services

解决方案


通常,REST API 将通过查询字符串传递参数,例如:

GET /resources?param1=value1&param2=value2.

您可以在 API 网关级别定义参数,如下所述:https ://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-settings-method-request.html#setup-method-request -参数

然后在您的 Lambda 代码中,您需要读取 API Gateway 在传入请求中传递的值,并使用它们来构建您的 DynamoDBparams对象。传入请求的确切格式在这里:https ://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for- lambda 输入格式

我建议您阅读本教程,它逐步解释了所有细节。https://docs.aws.amazon.com/apigateway/latest/developerguide/integrating-api-with-aws-services-lambda.html


推荐阅读