0
0
DynamodbHow-ToBeginner · 4 min read

How to Put Item in DynamoDB: Syntax and Example

To put an item in DynamoDB, use the PutItem operation specifying the table name and the item attributes as key-value pairs. This operation adds a new item or replaces an existing item with the same primary key.
📐

Syntax

The PutItem operation requires the TableName and an Item object containing attribute names and values. Optionally, you can use ConditionExpression to control when the item is added or replaced.

  • TableName: The name of your DynamoDB table.
  • Item: A map of attribute names to their values.
  • ConditionExpression (optional): A condition that must be true for the put to succeed.
json
{
  "TableName": "YourTableName",
  "Item": {
    "PrimaryKey": { "S": "key_value" },
    "Attribute1": { "S": "value1" },
    "Attribute2": { "N": "123" }
  },
  "ConditionExpression": "attribute_not_exists(PrimaryKey)" // optional
}
💻

Example

This example shows how to put an item into a DynamoDB table named Users with a primary key UserId and attributes Name and Age.

python
import boto3

# Create DynamoDB client
client = boto3.client('dynamodb')

# Put item into Users table
response = client.put_item(
    TableName='Users',
    Item={
        'UserId': {'S': 'user123'},
        'Name': {'S': 'Alice'},
        'Age': {'N': '30'}
    }
)

print('PutItem succeeded:', response)
Output
PutItem succeeded: {'ResponseMetadata': {'RequestId': '...', 'HTTPStatusCode': 200, 'HTTPHeaders': {...}, 'RetryAttempts': 0}}
⚠️

Common Pitfalls

Common mistakes when putting items in DynamoDB include:

  • Not specifying the primary key attributes correctly, causing errors or overwriting unintended items.
  • Using incorrect data types for attribute values (e.g., string instead of number).
  • Forgetting to handle conditional writes, which can cause overwrites if not intended.
  • Not setting up AWS credentials or permissions properly, leading to authorization errors.
python
import boto3

client = boto3.client('dynamodb')

# Wrong: Missing primary key attribute
try:
    client.put_item(
        TableName='Users',
        Item={
            'Name': {'S': 'Bob'},
            'Age': {'N': '25'}
        }
    )
except Exception as e:
    print('Error:', e)

# Right: Include primary key
client.put_item(
    TableName='Users',
    Item={
        'UserId': {'S': 'user456'},
        'Name': {'S': 'Bob'},
        'Age': {'N': '25'}
    }
)
Output
Error: An error occurred (ValidationException) when calling the PutItem operation: One or more parameter values were invalid: Missing the key UserId in the item
📊

Quick Reference

ParameterDescriptionExample
TableNameName of the DynamoDB table"Users"
ItemAttributes of the item as key-value pairs{"UserId": {"S": "user123"}, "Name": {"S": "Alice"}}
ConditionExpressionOptional condition to control write"attribute_not_exists(UserId)"
ReturnValuesWhat to return after put"NONE" or "ALL_OLD"

Key Takeaways

Always include the primary key attributes when putting an item in DynamoDB.
Use the correct data types for each attribute value (S for string, N for number, etc.).
PutItem replaces the entire item if the primary key already exists.
Use ConditionExpression to avoid overwriting existing items unintentionally.
Ensure AWS credentials and permissions are correctly configured before calling PutItem.