使用Curl将记录插入亚马逊的DynamoDB(通过低级API)

时间:2018-06-01 08:47:06

标签: amazon-web-services curl amazon-dynamodb aws-sdk libcurl

我尝试使用Curl将项目插入DynamoDB表。我知道有AWS SDK和AWS-CLI,但as per this document似乎也可以通过简单的HTTP API或Curl插入项目。

无论如何,我已经尝试了一段时间,但我不断收到此错误:

{"__type":"com.amazon.coral.service#SerializationException"}

有人可以告诉我我做错了吗?

这是我的剧本:

    $date = date('r');
    $priv_key = getenv('AWS_SECRET_ACCESS_KEY');
    $access_key = getenv('AWS_ACCESS_KEY_ID');
    $length = strlen($value);
    $signature = base64_encode(hash_hmac('sha256', $date, $priv_key, TRUE));

    $cmd = "curl -d @test.json -H \"Host: dynamodb.us-east-1.amazonaws.com;\" -H \"Accept-Encoding: identity\" -H \"Content-Length: $length\" -H \"User-Agent: Curl\" -H \"Content-Type: application/x-amz-json-1.0\" -H \"Authorization: $access_key:$signature\" -H \"X-Amz-Date: $date\" -H \"X-Amz-Target: DynamoDB_20120810.PutItem\" https://dynamodb.us-east-1.amazonaws.com\"";

    print ($cmd);
    print system($cmd);

以下是test.json(由Curl发送的文件)的内容

{
    "TableName": "cache",
    "Key": {
        "id": {"S": "1"},
        "data": {"S": "test"}
    }
}

我再次知道我可以很容易地通过SDK做到这一点,但我只是想知道为什么这不起作用?我根据文档做了一切,以了解SDK的内部工作原理。任何想法?

1 个答案:

答案 0 :(得分:1)

我唯一看到的错误是Content-Type应该是“ application \ json”。这是一个GetItem的工作示例:

curl -X POST \
  http://dynamodb.ap-southeast-2.amazonaws.com \
  -H 'Accept-Encoding: identity' \
  -H 'Authorization: AWS4-HMAC-SHA256 Credential=AKIAXXXXXXXXXXXXXXXX/20190505/ap-southeast-2/dynamodb/aws4_request, SignedHeaders=accept-encoding;cache-control;content-length;content-type;host;postman-token;user-agent;x-amz-date;x-amz-target, Signature=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' \
  -H 'Content-Length: 253' \
  -H 'Content-Type: application/json' \
  -H 'Host: dynamodb.ap-southeast-2.amazonaws.com' \
  -H 'Postman-Token: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' \
  -H 'User-Agent: postman' \
  -H 'X-Amz-Date: 20190505T235951Z' \
  -H 'X-Amz-Target: DynamoDB_20120810.GetItem' \
  -H 'cache-control: no-cache' \
  -d '{
   "TableName": "test-table",
   "Key": {
       "Eventdate": {
           "S": "2019-03-28"
       },
       "Eventid": {
           "S": "00001"
       }
   },
   "ConsistentRead": true,
   "ReturnConsumedCapacity": "TOTAL"
}'