1

I'm trying to insert data to DynamoDB directly with API Gateway. I can insert single, but get stuck with insert multiple data rows. May be problem with the mapping template (always get com.amazon.coral.service#SerializationException error)

  1. My dynamoDB table structure ex_table: time, column1, column2
  2. My gateway mapping template:
#set($inputRoot = $input.json('$.items')})
{
    "TableName": "ex_table",
    "Item":
    [
        #foreach($elem in $inputRoot) {
            "time": {"S": $input.json('$.time')},
            "column1": "$elem.column1.S",
            "column2": "$elem.column2.S",
        }#if($foreach.hasNext),#end
        #end
    ]
}
  1. And this is my request body:
{
  "time": "2021-03-31 16:50:00",
  "items": [
    {
      "column1": "Item1",
      "column2": "Attr1"
    },
    {
      "column1": "Item2",
      "column2": "Attr2"
    }
  ]
}

Can you guys help me this. Many thanks !

1 Answer 1

1

I think what you're looking for is "BatchWriteItem" in the DynamoDB API Reference. Instead of the normal Item{...} syntax for single writes, BatchWriteItem takes a slightly diff style:

{"RequestItems":{
    "TableName": [
        {"PutRequest" : {
            "Item": {
                "Name":{"S" : "Some Name"},
                "Category":{"S" : "Some Category"}
            }
        }},
        {"PutRequest" : {
            "Item": {
                "Name":{"S" : "Some Name 2"},
                "Category":{"S" : "Some Category 2"}
            }
        }}
    ]
}}

Combined with changing the action within APIGateway to BatchWriteItem and updating your mapping template like this (untested) should get you there (or close):

#set($inputRoot = $input.json('$.items')})
{
    "RequestItems": {
        "ex_table" : [
            #foreach($elem in $inputRoot) {
                "PutRequest" : {
                    "Item" : {
                        "time": {"S": $input.json('$.time')},
                        "column1": "$elem.column1.S",
                        "column2": "$elem.column2.S",
                    }
                }
            }#if($foreach.hasNext),#end
            #end
        ]
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.