Posting from AWS-API Gateway to Lambda

前端 未结 3 869
遇见更好的自我
遇见更好的自我 2020-12-29 11:19

I have a simple C# Aws Lambda function which succeeds to a test from the Lambda console test but fails with a 502 (Bad Gateway) if called from the API Gateway (which i gener

3条回答
  •  失恋的感觉
    2020-12-29 11:50

    This might not have been available when the OP asked the question, but when invoking a Lambda function using the API Gateway, specific response objects are provided.

    As previously noted in the documentation Api Gateway Simple Proxy for Lambda Input Format, the API Gateway wraps the input arguments in a fairly verbose wrapper. It also expects a similarly verbose response object.

    However, it is not necessary to create custom request and response objects. The AWS team provides the Amazon.Lambda.APIGatewayEvents library, which is also available on NuGet. This library includes APIGatewayProxyRequest and APIGatewayProxyResponse objects ready-made.

    It is still necessary to manually deserialize the Body of the request, as it is a string, not a JSON object. I assume this was done for flexibility?

    An example function could look like this. It's a modification of the default function provided by the AWS tools:

        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var bodyString = request?.Body;
    
            if (!string.IsNullOrEmpty(bodyString))
            {
                dynamic body = JsonConvert.DeserializeObject(bodyString);
    
                if (body.input != null)
                {
                    body.input = body.input?.ToString().ToUpper();
    
                    return new APIGatewayProxyResponse
                    {
                        StatusCode = 200,
                        Body = JsonConvert.SerializeObject(body)
                    };
                }
            }
    
            return new APIGatewayProxyResponse
            {
                StatusCode = 200
            };
        }
    

提交回复
热议问题