DynamoDB is a fully managed, serverless, key-value store NoSQL database as a service provided by AWS. DynamoDB can scale to any level while keeping response time in milliseconds. In this blog, we will learn how to put items into DynamoDB table using python and boto3.
Prerequisites
Before we start with putting items in the DynamoDB table, make sure you have the below things ready.
- I have already created the DynamoDB table in the AWS account. This table is named “orders,” and it has a primary key of “order_id” and the sort key of “order_date.” In this blog, you can learn how to create a DynamoDB table using AWS CDK.
- IAM user with the required permission to write data to DynamoDB table. You can learn how to create an IAM user and attach a policy to this blog.
- Configure this IAM user as an AWS profile on your machine. This blog goes through how to configure AWS profiles on your system.
- If you do not want to or can not configure the AWS profile on your machine, then you can use the IAM user’s access key ID and secret access key along with python and botot3. This blog reviews different ways we can use IAM credentials with python boto3.
I will use AWS CLI profile, Python, and boto3 to put items into the DynamoDB table.
Put Item into DynamoDB table
We can put items in the DyanomoDB table in two ways using Python and boto3.
- Using boto3 client, which is a low-level client to work with DynamoDB
- Using boto3 resource builds on top of DynamoDB client and is much easier to use.
Using both ways, we will learn how to put items in the DynamoDB table.
Put Item using boto3 client
Below code will insert an item in the DynamoDB table. Let us go over the code.
import boto3 boto3.setup_default_session(profile_name="ah") dynamodb_client = boto3.client("dynamodb") table_name = "orders" response = dynamodb_client.put_item( TableName=table_name, Item={ "order_id": {"S": "ord1234"}, "order_date": {"S": "2022-08-03"}, "user_email": {"S": "[email protected]"}, "amount": {"N": "120"}, }, ) print(response) # Output """ {'ResponseMetadata': {'RequestId': '81QL1EK656G8G4U063IG2G0Q0RVV4KQNSO5AEMVJF66Q9ASUAAJG', 'HTTPStatusCode': 200, 'HTTPHeaders': { 'server': 'Server', 'date': 'Wed, 03 Aug 2022 13:45:44 GMT', 'content-type': 'application/x-amz-json-1.0', 'content-length': '2', 'connection': 'keep-alive', 'x-amzn-requestid': '81QL1EK656G8G4U063IG2G0Q0RVV4KQNSO5AEMVJF66Q9ASUAAJG', 'x-amz-crc32': '2745614147' }, 'RetryAttempts': 0 } } """
When using the put_item function, Table name and Item are required parameters. The item must have a primary and sort key (if defined for the table).
We must pass them both as we have created a table with primary and sort keys. We are also passing additional data with item user_email and amount. When we run the above code, it will insert this item into the DynamoDB table.
We can also verify this in the AWS console.
Put item using boto3 DynamoDB resource
When using the client, we must pass type information for each item property when putting data into the DynamoDB table. It quickly becomes cumbersome. Instead of a client, we can use the boto3 resource to put items. Let us go over the code for that.
import boto3 import json boto3.setup_default_session(profile_name="ah") table_name = "orders" def put_item_using_resource(): dynamodb_resource = boto3.resource("dynamodb") table = dynamodb_resource.Table(table_name) response = table.put_item( Item={ "order_id": "ord1235", "order_date": "2022-08-03", "user_email": "[email protected]", "amount": 67, "payment_mode": "credit_card", } ) print(json.dumps(response, indent=2)) put_item_using_resource()
We added another item to the DynamoDB table in the above code. You can see that it is much easier to add items using the DynamoDB boto3 resource. We do not have to add type information along with values.
We also have added a new parameter, “payment_mode,” in this item. This is an advantage of having a flexible schema. Let us verify that on the AWS console.
Additional Data in put_item Response
Upon writing items into the DynamoDB table, we get a response. When we print it (See code example 1), there is not much useful information in response. But we can ask for more information to be returned after inserting items into the DynamoDB table. Let us go over the below code and see how we can achieve that.
def put_item_using_resource(): dynamodb_resource = boto3.resource("dynamodb") table = dynamodb_resource.Table(table_name) response = table.put_item( Item={ "order_id": "ord1236", "order_date": "2022-08-03", "user_email": "[email protected]", "amount": 157, }, ReturnConsumedCapacity="TOTAL" ) print(json.dumps(response, indent=2)) #output { "ConsumedCapacity": { "TableName": "orders", "CapacityUnits": 1.0 }, "ResponseMetadata": { "RequestId": "MK6BD6N2PT3BQGEKN1UJ85HOQVVV4KQNSO5AEMVJF66Q9ASUAAJG", "HTTPStatusCode": 200, "HTTPHeaders": { "server": "Server", "date": "Wed, 03 Aug 2022 14:33:32 GMT", "content-type": "application/x-amz-json-1.0", "content-length": "63", "connection": "keep-alive", "x-amzn-requestid": "MK6BD6N2PT3BQGEKN1UJ85HOQVVV4KQNSO5AEMVJF66Q9ASUAAJG", "x-amz-crc32": "210231213" }, "RetryAttempts": 0 } }
When we pass ReturnConsumedCapacity=”TOTAL” in the put_item call, we receive the total consumed capacity used for this action. This is useful for logging. We can also pass ReturnItemCollectionMetrics and ReturnValues in the put_item call, but those are more useful when updating items.
Conclusion
In this blog, we have learned how to insert items into the DynamoDB table using Python. The following blog will be about conditional inserts into the DynamoDB table. See you there.