Skip to content

How To Insert Data Into a DynamoDB Table with Boto3

DynamoDB is used for many use cases, including web and mobile applications, gaming, ad tech, IoT, and more. It is particularly well-suited for applications that require low latency, high scalability, and flexible data modeling.

It is designed to be highly scalable and performant and can handle millions of requests per second. It is used for many use cases, including web and mobile applications, gaming, ad tech, IoT, and more.

DynamoDB is particularly well-suited for applications that require low latency, high scalability, and flexible data modeling.

Know more about: How to Install and Upgrade the AWS CDK CLI

It achieves high availability and reliability through automatic data replication across multiple availability zones and through the use of advanced techniques such as consistent hashing and gossip protocols.

This article will teach you to insert data into the DynamoDB table using Boto3. But before diving deep into it, look at the prerequisites you need.

Prerequisites

  1. You need an AWS IAM account
  2. To Interreact with DynamoDB, you require the dynamodb:PutItem permission in your IAM policy.

Import Boto3

Boto3 is a Python SDK that allows you to interact with DynamoDB APIs. To import Boto3, run the below single-line command:

import boto3

After importing, you need to get a reference to the DynamoDB resources.

Get Reference to the DynamoDB Resources

You can use DynamoDB resources or Client Object, whatever you want. However, we are going to use DynamoDB resources in this article.

The resource object offers higher-level APIs, which make it easier to access. Additionally, it is the more modern way of interacting with the Dynamo.

Check out this also: Ingesting and Monitoring Custom Metrics in CloudWatch With AWS Lambda

Sometimes resources may not always be up to date, and you can alternatively use the client. The client offers more verbose lower, level APIs.

I suggest you use the resource object for all your interactions with Dynamo. Run the following command to get the reference:

dynamodb = boto3.resource('dynamodb')

Get a Reference to the DynamoDB Table

Next, you need to get a reference to the DynamoDB table also. I’m using Lambda (a popular AWS Service) interreact with DynamoDB. Run the following command to complete this step:

def lambda_handler(event, context):
    table = dynamodb.Table('Countries')

Perform Insert Operation

Before inserting your data into DynamoDB, you might have to prepare it by pre-processing. The good thing about using the resource object is that it automatically converts your Python data types into the correct DynamoDB types.

For instance, if you provide an integer, it will use the Number field as the DynamoDB type, and the same goes for strings, lists, booleans, and so on.

Read also: How to Host Static Websites on AWS S3?

Use the below-put item command to perform the insert operation:

 response = table.put_item(
        Item={
            'CountryName': 'Canada',
            'Population': 30000000
        }
    )

Don’t run this command multiple times, which will overwrite all the records. If you want to update an existing object’s field, you should use the UpdateItem API.

After running the command, you will see the record in your DynamoDB table like below:

 The DynamoDB table shows the new record after running the above command.
The DynamoDB table shows the new record after running the above command.

After you finish a task, you must check the HTTP status code in the response object to confirm the successful operation. We’re specifically looking for a 200 OK status code indicating success. You can verify this by using the provided code.

status_code = response['ResponseMetadata']['HTTPStatusCode']

You might also want to print out the response object to see some additional features, such as the number of times DynamoDB tried to complete the task internally (if needed) and the request.

Here’s the complete code that combines all these code snippets:

import boto3

dynamodb = boto3.resource('dynamodb')

def lambda_handler(event, context):
    table = dynamodb.Table('Countries')

    response = table.put_item(
        Item={
            'CountryName': 'Canada',
            'Population': 30000000
        }
    )
    
    status_code = response['ResponseMetadata']['HTTPStatusCode']
    print(status_code)

Put Item into DynamoDB Table using boto3 client

When using the put_item function, you must provide two essential information pieces: the table name and the item. The item must have a primary key; if the table has a sort key, it should also have that.

In our code, we pass the table name and item, including additional data such as user_email and amount. After running the code, the item will be inserted into the DynamoDB table.

The below command will insert an item into the DynamoDB table:

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": "test@example.com"},
        "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
  }
}
"""

You can confirm this by checking the AWS console.

Item inserted into DynamoDB using boto3 client
Item inserted into DynamoDB using boto3 client

This article teaches how to insert data into a DynamoDB Table with Boto3. To get updated, subscribe to our newsletter.

https://beabetterdev.com/2022/02/22/how-to-insert-into-a-dynamodb-table-with-boto3/

https://binaryguy.tech/aws/dynamodb/put-items-into-dynamodb-table-using-python/

Share This Article On:

Other Related Topics

Getting Started with Amazon Redshift in 6 Simple Steps

How to Install and Upgrade the AWS CDK CLI

Ingesting and Monitoring Custom Metrics in CloudWatch With AWS Lambda

Microsoft Azure vs AWS vs Google Cloud – Comparison

How to Host Static Websites on AWS S3?

How to Choose the Right Cloud Service Provider?​