简体   繁体   English

如何使用AWS API Gateway将URL参数传递给Lambda函数?

[英]How do you pass URL Parameters to a Lambda function using AWS API Gateway?

I am currently trying to create a Hello World Lambda function and test it through the API Gateway, as my intent is to provide a REST API using Lambda function. 我目前正在尝试创建Hello World Lambda函数并通过API网关对其进行测试,因为我的意图是使用Lambda函数提供REST API。 I have a very basic function handler that takes in an integer and outputs it as a string: 我有一个非常基本的函数处理程序,它接受一个整数并将其输出为字符串:

     public string FunctionHandler(int input, ILambdaContext context)
    {
        return input.ToString();
    }

I have published this code to AWS and it seems to work. 我已将此代码发布到AWS,并且似乎可以正常工作。 I have tested it from Visual Studio using the AWS tools as well as from the AWS Console. 我已经使用AWS工具从Visual Studio以及AWS控制台对其进行了测试。

I have an API setup that has a POST method with a single resource parameter called "input". 我有一个API设置,该API的POST方法带有一个称为“输入”的资源参数。 When creating the method I selected Lambda Expression for Integration Type. 创建方法时,我为集成类型选择了Lambda表达式。

When I use the API Test screen to test it out, I always receive a JSON exception. 当我使用API​​测试屏幕进行测试时,总是会收到JSON异常。 Here is the output: 这是输出:

{
"errorType": "JsonReaderException",
"errorMessage": "Unexpected character encountered while parsing value: {.   Path '', line 1, position 1.",
"stackTrace": [
"at Newtonsoft.Json.JsonTextReader.ReadNumberValue(ReadType readType)",
"at Newtonsoft.Json.JsonTextReader.ReadAsInt32()",
"at  Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)",
"at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)",
"at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)",
"at Newtonsoft.Json.JsonSerializer.Deserialize[T](JsonReader reader)",
"at lambda_method(Closure , Stream , Stream , ContextInfo )"
]
}

Here are the headers that are logged as well. 这也是记录的标头。 They show the value that I am providing for input, in this case a 1: 它们显示了我为输入提供的值,在这种情况下为1:

Execution log for request test-request
Wed Jan 03 19:12:25 UTC 2018 : Starting execution for request: test-invoke-request
Wed Jan 03 19:12:25 UTC 2018 : HTTP Method: POST, Resource Path: /1
Wed Jan 03 19:12:25 UTC 2018 : Method request path: {input=1}
Wed Jan 03 19:12:25 UTC 2018 : Method request query string: {}
Wed Jan 03 19:12:25 UTC 2018 : Method request headers: {}

I dont really understand why I am receiving any sort of JSON errors. 我真的不明白为什么我会收到任何JSON错误。 When I test via the console or Visual Studio, I simply provide a "1". 通过控制台或Visual Studio进行测试时,只需提供“ 1”即可。 No JSON formatting at all. 完全没有JSON格式。 When I test via the Console using path parameters it should essentially be a url like "mydomain.com/resource/1". 当我使用路径参数通过控制台进行测试时,它实际上应该是一个网址,例如“ mydomain.com/resource/1”。 It shouldnt need to parse it, but I am sure there is a good reason for it to try. 它不需要解析它,但是我相信有充分的理由尝试它。

Is it even possible to pass path parameters to a Lambda function? 甚至可以将路径参数传递给Lambda函数吗?

Thanks 谢谢

I believe I have figured this out. 我相信我已经弄清楚了。 I noticed that many people in similar threads were suggesting either using a Mapping Template to send the data in whatever format I wanted or selecting Use Lambda Proxy Integration . 我注意到,许多处于类似话题的人都建议使用映射模板以我想要的任何格式发送数据,或者选择“ 使用Lambda代理集成” Either one of these suggestions will work, but what is confusing is how to handle it using the C# SDK. 这些建议中的任何一个都将起作用,但是令人困惑的是如何使用C#SDK处理它。

The first parameter of your FunctionHandler will be a JObject containing the json in the request body. 您的FunctionHandler的第一个参数将是一个在请求正文中包含json的JObject。 If you dont have a mapping template and you dont select Use Lambda Proxy Integration, this will always be empty. 如果您没有映射模板,并且没有选择“使用Lambda代理集成”,则该字段将始终为空。 I decided to go with USe Lambda Proxy Integration because it seems to provide all of the details I need in well-formatted JSON. 我决定使用USe Lambda代理集成,因为它似乎以格式良好的JSON提供了我需要的所有详细信息。

The second important thing to note is that there is already a class that can be used to automatically deserialize the json. 要注意的第二件事是已经有一个类可以用于自动反序列化json。 It provides the path params, querystring, body, and headers as simple properties that you can easily access. 它提供路径参数,查询字符串,正文和标头作为您可以轻松访问的简单属性。 That is the Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest (you will probably need to add the nuget package since it isnt a part of the default empty template). 那就是Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest (您可能需要添加nuget包,因为它不是默认空模板的一部分)。

So in the end my code looks like this: 因此,最终我的代码如下所示:

    public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
    {

        context.Logger.LogLine("Get Request\n");
        var path = "none";
        if (request.PathParameters != null && request.PathParameters.Any())
        {
            path = request.PathParameters["input"];
        }
        var response = new APIGatewayProxyResponse
        {
            StatusCode = (int)HttpStatusCode.OK,
            Body = "Hello World. Here are is your path param: " + path,
            Headers = new Dictionary<string, string> { { "Content-Type", "application/json" }, { "Access-Control-Allow-Origin", "*" } }
        };
        return response;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 API 网关将事件参数传递给 AWS Lambda function? - How to pass event parameters to AWS Lambda function using API Gateway? 如何使用aws中的cloudformation在api网关中请求参数并将其传递给lambda函数? - How can I request parameters in api gateway using cloudformation in aws and pass it down to lambda function? 如何使用 API Gateway 使用凭证访问 AWS Lambda? - How do you access an AWS Lambda with credentials using API Gateway? C#如何配置AWS API Gateway参数以映射到基本的AWS Lambda函数? - C# How do i configure AWS API Gateway parameters to map to a basic AWS Lambda Function? 如何使用Javascript SDK将查询字符串参数传递给AWS API Gateway客户端? - How do you pass query string parameters to the AWS API Gateway client with the Javascript SDK? 如何将POST变量传递给运行Lambda函数的AWS API Gateway? - How to pass POST variables to an AWS API Gateway running a lambda function? 如何使用API​​网关将参数传递给Lambda函数以从DynamoDB查询项目? - How to pass parameters to a Lambda function using API gateway for querying items from DynamoDB? 如何使用 AWS CDK 将阶段变量传递给 api 网关中的 lambda 函数? - How to pass a stage variable to lambda function in api gateway using AWS CDK? 如何对通过AWS API Gateway端点调用/写入dynamodb并调用的NodeJs Lambda函数进行单元测试? - How do you unit test a NodeJs Lambda function that writes/reads to dynamodb and is invoked via an AWS API Gateway endpoint? 如何将数据从AWS API Gateway自定义授权者传递到AWS Lambda函数? - How to pass data from AWS API Gateway Custom Authorizer to an AWS Lambda function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM