简体   繁体   中英

C# How do i configure AWS API Gateway parameters to map to a basic AWS Lambda Function?

I'm new to using AWS and cloud services in general but I'm trying to create a backend that handles get items from a DynamodDB and if they don't exist create them. I'm trying to accomplish this by using API gateway to call the lambda and using the lambda to handle the work on the DB. I've created a sort of sample lambda that scans the database and returns a string. I did this using the AWS lambda project in visual studios. When giving it sample input of a string in both visual studios and the test events on the lambda designer it works fine and returns a string containing the expected results. So I tried adding a new API as a trigger and I cannot figure out how to configure it to send the proper input. I've been working on this for hours and I can't find any information pertaining to sending data as parameters to the lambda. When I try to run the api in my browsers I get {"message": "Internal server error"}. When I test it on the api gateway I get this.

Sat Mar 17 18:50:38 UTC 2018 : Endpoint response body before transformations: {
"errorType": "JsonReaderException",
"errorMessage": "Unexpected character encountered while parsing value: {. 
Path '', line 1, position 1.",
"stackTrace": [
"at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)",
"at Newtonsoft.Json.JsonTextReader.ReadAsString()",
"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 Amazon.Lambda.Serialization.Json.JsonSerializer.Deserialize[T](Stream 
requestStream)",
"at lambda_method(Closure , Stream , Stream , LambdaContextInternal )"
]
}

Sat Mar 17 18:50:38 UTC 2018 : Endpoint response headers: {X-Amz-Executed- 
Version=$LATEST, x-amzn-Remapped-Content-Length=0, Connection=keep-alive, x- 
amzn-RequestId=15d89cfe-2a14-11e8-982c-db6e675f8b1d, Content-Length=939, X- 
Amz-Function-Error=Unhandled, Date=Sat, 17 Mar 2018 18:50:38 GMT, X-Amzn- 
Trace-Id=root=1-5aad637e-629010f757ae9b77679f6f40;sampled=0, Content- 
Type=application/json}
Sat Mar 17 18:50:38 UTC 2018 : Execution failed due to configuration error: 
Malformed Lambda proxy response
Sat Mar 17 18:50:38 UTC 2018 : Method completed with status: 502

Below is a copy of my lambda and I configured the API by adding it as a trigger and setting it to open security. I just don't understand how to set the params to target input.

TESTLAMBDA

[assembly:LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace FindItem
{
public class Function
{

    /// <summary>
    /// A simple function that takes a string and does a ToUpper
    /// </summary>
    /// <param name="input"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public string FunctionHandler(string input, ILambdaContext context)
    {

        AmazonDynamoDBClient client = GetClient();

        Table table = GetTableObject(client, "Stores");
        if (table == null)
        {
            PauseForDebugWindow();
            return "Failure";
        }

        ScanFilter filter = new ScanFilter();
        filter.AddCondition("Item_name", ScanOperator.Contains, new DynamoDBEntry[] { input });
        ScanOperationConfig config = new ScanOperationConfig
        {
            AttributesToGet = new List<string> { "Store, Item_name, Aisle, Price" },
            Filter = filter
        };

        Search search = table.Scan(filter);
        List<Document> docList = new List<Document>();

        Task<String> obj = traversedoc(docList,search);

        return obj.Result;
    }


    /// /////////////////////////////////////////////////////////////////////////

    public async Task<String> traversedoc(List<Document>docList,Search search)
    {

        string astring = "";

        do
        {
            try
            {
                docList = await search.GetNextSetAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n Error: Search.GetNextStep failed because: " + ex.Message);
                break;
            }
            foreach (var doc in docList)
            {

                 astring = astring + doc["Store"] + doc["Item_name"] + doc["Aisle"] + doc["Price"];

            }
        } while (!search.IsDone);

        return astring;

    }

    public static AmazonDynamoDBClient GetClient()
    {
        // First, set up a DynamoDB client for DynamoDB Local
        AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig();
        AmazonDynamoDBClient client;
        try
        {
            client = new AmazonDynamoDBClient(ddbConfig);
        }
        catch (Exception ex)
        {
            Console.WriteLine("\n Error: failed to create a DynamoDB client; " + ex.Message);
            return (null);
        }
        return (client);



    }


    public static Table GetTableObject(AmazonDynamoDBClient client, string tableName)
    {
        Table table = null;
        try
        {
            table = Table.LoadTable(client, tableName);
        }
        catch (Exception ex)
        {
            Console.WriteLine("\n Error: failed to load the 'Movies' table; " + ex.Message);
            return (null);
        }
        return (table);
    }

    public static void PauseForDebugWindow()
    {
        // Keep the console open if in Debug mode...
        Console.Write("\n\n ...Press any key to continue");
        Console.ReadKey();
        Console.WriteLine();
    }


}
}

It turned out that Lambda Proxy Integration was checked. This was under my resources method in integration request. I'm particularly sure what that did but once I unchecked that I was able to send request body only with the post method. So now when I send only text("milk") in request body its received as my input string parameter and functions properly!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM