Amazon DynamoDB: Insert an Item Without Overwriting
See more Amazon DynamoDB Examples
Live write: use attribute_not_exists on the partition-key attribute. The condition is evaluated on the item identified by the complete PK/SK pair, so other sort keys in that partition are allowed. ConditionalCheckFailedException means this request did not replace the item.
Without the condition, PutItem replaces the entire matching item; omitted attributes disappear. Use UpdateItem to change selected attributes. Demonstrates strings, precise numeric strings, Boolean, and string set. Sets cannot be empty or contain duplicate members. Empty non-key strings are allowed. Stored item size is limited to 400 KB, including attribute names.
The item examples use the ExampleItems table from Create a Table, with string partition key PK and string sort key SK. Wait for ACTIVE. DynamoDB AttributeValue JSON uses wrappers such as {"S":"text"}, {"N":"123.45"}, and {"BOOL":true}. Numeric attributes travel as strings; preserve their precision rather than converting them to int or floating point. Names and IDs remain strings.
Uses DynamoDB's regional JSON API: POST to /, application/x-amz-json-1.0, and an operation-specific X-Amz-Target: DynamoDB_20120810... header. The 20120810 API identifier is still current. Chilkat.Rest and AuthAws sign each request with AWS Signature Version 4, service dynamodb. Set the region once; the example builds the matching commercial AWS endpoint. Other AWS partitions use their own endpoint suffixes.
Read current IAM credentials from a private qa_data/aws/dynamodb.json containing string fields access_key, secret_key, and, for temporary credentials, session_token. Prefer short-lived role credentials and refresh them before expiry. This code explicitly reads the file; it does not discover an AWS profile or refresh credentials automatically. The session token is included in the signed X-Amz-Security-Token query parameter, so keep request URLs and diagnostics private. A Socket explicitly enables TLS certificate verification and is supplied to Rest. Reuse the configured Rest object for subsequent requests.
Required IAM action: dynamodb:PutItem. Restrict access to the intended table ARN; an index query also needs the appropriate index ARN.
Checks transport completion, HTTP 200, and JSON validity separately. DynamoDB errors include __type and message. HTTP 400 can mean throttling, failed conditions, invalid input, or expired credentials. Use bounded exponential backoff with jitter for retryable failures; renew expired credentials. A failed condition requires an application decision, not an automatic retry. For writes with an uncertain outcome, read/reconcile before retrying. This sample does not automatically replay writes.
Chilkat PowerBuilder Downloads
integer li_rc
long li_Success
oleobject loo_Credentials
string ls_Region
oleobject loo_Endpoint
oleobject loo_Aws
oleobject loo_Rest
oleobject loo_Connection
oleobject loo_Body
oleobject loo_Result
oleobject loo_RequestBody
oleobject loo_ResponseBody
string ls_TableName
oleobject loo_ErrorType
li_Success = 0
// Assumes Chilkat is unlocked. See Global Unlock Sample.
li_Success = 0
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the DynamoDB operation.
loo_Credentials = create oleobject
li_rc = loo_Credentials.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
destroy loo_Credentials
MessageBox("Error","Connecting to COM object failed")
return
end if
loo_Credentials.Strict = 1
li_Success = loo_Credentials.LoadFile("qa_data/aws/dynamodb.json")
if li_Success <> 1 then
Write-Debug "Could not load private AWS credentials."
destroy loo_Credentials
return
end if
if (loo_Credentials.JsonTypeOf("access_key") <> 1) OR (loo_Credentials.StringOf("access_key") = "") then
Write-Debug "Missing or invalid access_key."
destroy loo_Credentials
return
end if
if (loo_Credentials.JsonTypeOf("secret_key") <> 1) OR (loo_Credentials.StringOf("secret_key") = "") then
Write-Debug "Missing or invalid secret_key."
destroy loo_Credentials
return
end if
// Set this once to the region containing the table.
ls_Region = "us-west-2"
loo_Endpoint = create oleobject
li_rc = loo_Endpoint.ConnectToNewObject("Chilkat.StringBuilder")
loo_Endpoint.Append("dynamodb.")
loo_Endpoint.Append(ls_Region)
loo_Endpoint.Append(".amazonaws.com")
loo_Aws = create oleobject
li_rc = loo_Aws.ConnectToNewObject("Chilkat.AuthAws")
loo_Aws.AccessKey = loo_Credentials.StringOf("access_key")
loo_Aws.SecretKey = loo_Credentials.StringOf("secret_key")
loo_Aws.Region = ls_Region
loo_Aws.ServiceName = "dynamodb"
loo_Aws.SignatureVersion = 4
loo_Rest = create oleobject
li_rc = loo_Rest.ConnectToNewObject("Chilkat.Rest")
loo_Rest.ConnectTimeoutMs = 20000
loo_Rest.IdleTimeoutMs = 60000
li_Success = loo_Rest.SetAuthAws(loo_Aws)
if li_Success <> 1 then
Write-Debug "Could not configure AWS signing."
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
return
end if
// Temporary IAM/STS credentials require their session token on every signed request.
// AddQueryParam includes it in SigV4's canonical query. Never log the request URL.
// Leave session_token absent or empty only for credentials that do not have one.
if loo_Credentials.HasMember("session_token") = 1 then
if loo_Credentials.JsonTypeOf("session_token") <> 1 then
Write-Debug "session_token must be a string."
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
return
end if
if loo_Credentials.StringOf("session_token") <> "" then
li_Success = loo_Rest.AddQueryParam("X-Amz-Security-Token",loo_Credentials.StringOf("session_token"))
if li_Success <> 1 then
Write-Debug "Could not set the session-token parameter."
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
return
end if
end if
end if
// Supply a Socket to explicitly enable TLS certificate verification.
loo_Connection = create oleobject
li_rc = loo_Connection.ConnectToNewObject("Chilkat.Socket")
loo_Connection.RequireSslCertVerify = 1
loo_Connection.MaxReadIdleMs = 60000
loo_Connection.MaxSendIdleMs = 60000
li_Success = loo_Connection.Connect(loo_Endpoint.GetAsString(),443,1,20000)
if li_Success <> 1 then
Write-Debug "TLS connection failed; inspect diagnostics privately."
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
return
end if
li_Success = loo_Rest.UseConnection(loo_Connection,1)
if li_Success <> 1 then
Write-Debug "Could not attach the TLS connection."
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
return
end if
li_Success = loo_Rest.AddHeader("Content-Type","application/x-amz-json-1.0")
if li_Success <> 1 then
Write-Debug "Could not set the content type."
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
return
end if
loo_Body = create oleobject
li_rc = loo_Body.ConnectToNewObject("Chilkat.JsonObject")
loo_Result = create oleobject
li_rc = loo_Result.ConnectToNewObject("Chilkat.JsonObject")
loo_Result.Strict = 1
loo_RequestBody = create oleobject
li_rc = loo_RequestBody.ConnectToNewObject("Chilkat.StringBuilder")
loo_ResponseBody = create oleobject
li_rc = loo_ResponseBody.ConnectToNewObject("Chilkat.StringBuilder")
li_Success = loo_Rest.AddHeader("X-Amz-Target","DynamoDB_20120810.PutItem")
if li_Success <> 1 then
Write-Debug "Could not set the DynamoDB operation."
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_RequestBody
destroy loo_ResponseBody
return
end if
ls_TableName = "ExampleItems"
loo_Body.UpdateString("TableName",ls_TableName)
// Insert only if this complete PK/SK pair is absent.
// N values are decimal strings; SS is a nonempty set of unique strings.
loo_Body.UpdateString("Item.PK.S","group-1")
loo_Body.UpdateString("Item.SK.S","item-001")
loo_Body.UpdateString("Item.Data.S","Initial value")
loo_Body.UpdateString("Item.Version.N","1")
loo_Body.UpdateString("Item.Amount.N","123.45")
loo_Body.UpdateBool("Item.Enabled.BOOL",1)
loo_Body.UpdateString("Item.Tags.SS[0]","example")
loo_Body.UpdateString("Item.Tags.SS[1]","sample")
loo_Body.UpdateString("ConditionExpression","attribute_not_exists(#pk)")
loo_Body.UpdateString("ExpressionAttributeNames.#pk","PK")
loo_Body.UpdateString("ReturnConsumedCapacity","TOTAL")
// EmitSb appends. Clear the request buffer before each request/page.
loo_RequestBody.Clear()
li_Success = loo_Body.EmitSb(loo_RequestBody)
if li_Success <> 1 then
Write-Debug "Could not encode the request."
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_RequestBody
destroy loo_ResponseBody
return
end if
li_Success = loo_Rest.FullRequestSb("POST","/",loo_RequestBody,loo_ResponseBody)
if li_Success <> 1 then
Write-Debug "Request did not complete; inspect diagnostics privately."
// A write may already have succeeded. Reconcile its outcome before retrying.
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_RequestBody
destroy loo_ResponseBody
return
end if
if loo_Rest.ResponseStatusCode <> 200 then
Write-Debug "DynamoDB HTTP status: " + string(loo_Rest.ResponseStatusCode)
li_Success = loo_Result.LoadSb(loo_ResponseBody)
if li_Success = 1 then
if loo_Result.JsonTypeOf("__type") = 1 then
loo_ErrorType = create oleobject
li_rc = loo_ErrorType.ConnectToNewObject("Chilkat.StringBuilder")
loo_ErrorType.Append(loo_Result.StringOf("__type"))
Write-Debug "AWS error type: " + loo_ErrorType.GetAsString()
if loo_ErrorType.EndsWith("ConditionalCheckFailedException",1) = 1 then
Write-Debug "Condition failed; this request made no change. Re-read the item before deciding what to do."
end if
end if
end if
// Throttling can be HTTP 400. Inspect __type, not just the HTTP status.
// Keep full error messages, item data, and signed request diagnostics private.
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_RequestBody
destroy loo_ResponseBody
destroy loo_ErrorType
return
end if
li_Success = loo_Result.LoadSb(loo_ResponseBody)
if li_Success <> 1 then
Write-Debug "Expected a well-formed JSON response."
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_RequestBody
destroy loo_ResponseBody
destroy loo_ErrorType
return
end if
Write-Debug "Item inserted without replacing an existing item."
if loo_Result.HasMember("ConsumedCapacity.CapacityUnits") = 1 then
// Capacity can be fractional; do not truncate it with IntOf.
Write-Debug "Consumed capacity: " + loo_Result.StringOf("ConsumedCapacity.CapacityUnits")
end if
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_RequestBody
destroy loo_ResponseBody
destroy loo_ErrorType