How To Insert Data Into a DynamoDB Table with Boto3

Posted on Oct 11, 2023

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/

How To Insert Data Into a DynamoDB Table with Boto3
Binaya Puri

Latest Blogs

New AWS Announcement for October 2023

New AWS Announcement for October 2023


New AWS Announcement for October 2023

Adex International

Nov 08, 2023

Sustainability in the AWS Well-Architected Framework: A Comprehensive Guide

Sustainability in the AWS Well-Architected Framework: A Comprehensive Guide


Sustainability in the AWS Well-Architected Framework: A Comprehensive Guide

Adex International

Oct 19, 2023

AWS New Announcement Sept 2023

AWS New Announcement Sept 2023


AWS New Announcement Sept 2023

Adex International

Oct 17, 2023

Migrate Gitlab PostgreSQL Database to Custom Location Using Ansible

Migrate Gitlab PostgreSQL Database to Custom Location Using Ansible


Migrate Gitlab PostgreSQL Database to Custom Location Using Ansible

Saugat Tiwari

Oct 11, 2023

Mastering DevOps: Your Ultimate Guide to DevOps Managed Services

Mastering DevOps: Your Ultimate Guide to DevOps Managed Services


Mastering DevOps: Your Ultimate Guide to DevOps Managed Services

Biswash Giri

Oct 11, 2023

Discover the Benefits of Security as a Service (SECaaS) for your Business

Discover the Benefits of Security as a Service (SECaaS) for your Business


Discover the Benefits of Security as a Service (SECaaS) for your Business

Saugat Tiwari

Oct 11, 2023

Port Forwarding Using AWS System Manager Session Manager

Port Forwarding Using AWS System Manager Session Manager


Port Forwarding Using AWS System Manager Session Manager

Saugat Tiwari

Oct 11, 2023

Maximizing Directory Services with LDAP: Creating OUs, Groups, and Users for Improved Authentication and Access Control

Maximizing Directory Services with LDAP: Creating OUs, Groups, and Users for Improved Authentication and Access Control


Maximizing Directory Services with LDAP: Creating OUs, Groups, and Users for Improved Authentication and Access Control

Biswash Giri

Oct 11, 2023

AWS Migration Tools: A Comprehensive Guide

AWS Migration Tools: A Comprehensive Guide

IntroductionAWS migration tools are a comprehensive set of services and utilities provided by Amazon...


AWS Migration Tools: A Comprehensive Guide

Binaya Puri

Oct 11, 2023

Difference Between AWS Cloudwatch and Cloudtrail

Difference Between AWS Cloudwatch and Cloudtrail

AWS CloudWatch and AWS CloudTrails are sometimes difficult to distinguish. This article seeks to d...


Difference Between AWS Cloudwatch and Cloudtrail

Sabin Joshi

Oct 11, 2023

New AWS Announcements for June 2023 - Adex

New AWS Announcements for June 2023 - Adex


New AWS Announcements for June 2023 - Adex

Ravi Gupta

Oct 11, 2023

Top 7 Applications Of Cloud Computing In Various Field

Top 7 Applications Of Cloud Computing In Various Field


Top 7 Applications Of Cloud Computing In Various Field

Susmita Karki Chhetri

Oct 11, 2023

Ingesting and Monitoring Custom Metrics in CloudWatch With AWS Lambda

Ingesting and Monitoring Custom Metrics in CloudWatch With AWS Lambda


Ingesting and Monitoring Custom Metrics in CloudWatch With AWS Lambda

Tej pandey

Oct 11, 2023

7 Types of Security in Cloud Computing?

7 Types of Security in Cloud Computing?


7 Types of Security in Cloud Computing?

Mukesh Awasthi

Oct 11, 2023

Cost-effective Use cases & Benefits of Amazon S3

Cost-effective Use cases & Benefits of Amazon S3


Cost-effective Use cases & Benefits of Amazon S3

Nischal Gautam

Oct 11, 2023

IT Outsourcing: Everything You Need To Know

IT Outsourcing: Everything You Need To Know

The world has changed, and as technology advances, so does the world of work. Gone are the day...


IT Outsourcing: Everything You Need To Know

Roshan Raman Giri

Oct 11, 2023

Getting Started with Amazon Redshift in 6 Simple Steps

Getting Started with Amazon Redshift in 6 Simple Steps


Getting Started with Amazon Redshift in 6 Simple Steps

Tej pandey

Oct 11, 2023

How to Host Static Websites on AWS S3?

How to Host Static Websites on AWS S3?

How to Host Static Websites on AWS S3? Hosting a Static Website on AWS S3 has a lot of benefits....


How to Host Static Websites on AWS S3?

Ravi Gupta

Oct 11, 2023

The Importance of Managed Cloud Security for Businesses

The Importance of Managed Cloud Security for Businesses


The Importance of Managed Cloud Security for Businesses

Roshan Raman Giri

Oct 11, 2023

How To Use Amazon S3 For Personal Backup?

How To Use Amazon S3 For Personal Backup?


How To Use Amazon S3 For Personal Backup?

Tej pandey

Oct 11, 2023

Major AWS Updates &Announcements of 2023 - March

Major AWS Updates &Announcements of 2023 - March


Major AWS Updates &Announcements of 2023 - March

Roshan Raman Giri

Oct 11, 2023

How To Insert Data Into a DynamoDB Table with Boto3

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,...


How To Insert Data Into a DynamoDB Table with Boto3

Binaya Puri

Oct 11, 2023

How to Install and Upgrade the AWS CDK CLI

How to Install and Upgrade the AWS CDK CLI


How to Install and Upgrade the AWS CDK CLI

Nischal Gautam

Oct 11, 2023

Ultimate Guide on Creating Terraform Modules

Ultimate Guide on Creating Terraform Modules


Ultimate Guide on Creating Terraform Modules

Tej pandey

Oct 11, 2023

What is serverless computing?

What is serverless computing?


What is serverless computing?

Tej pandey

Oct 11, 2023

AWS Well-Architected Framework Security Pillar

AWS Well-Architected Framework Security Pillar

The Amazon Well-Architected Framework is a set of recommendations and practice guidelines for develo...


AWS Well-Architected Framework Security Pillar

Binaya Puri

Oct 11, 2023

Amazon FSx for Lustre, Windows, and NetApp ONTAP

Amazon FSx for Lustre, Windows, and NetApp ONTAP

Amazon FSx for Lustre, Windows, and NetApp ONTAPAmazon FSx is known for its fully managed, hig...


Amazon FSx for Lustre, Windows, and NetApp ONTAP

Ravi Gupta

Oct 11, 2023

How to Choose the Right Cloud Service Provider?

How to Choose the Right Cloud Service Provider?


How to Choose the Right Cloud Service Provider?

Tej pandey

Oct 11, 2023

25 New AWS Services Updates from AWS Re:Invent 2022

25 New AWS Services Updates from AWS Re:Invent 2022


25 New AWS Services Updates from AWS Re:Invent 2022

Susmita Karki Chhetri

Oct 11, 2023

AWS Managed Hosting Services And Dedicated Hosting Benefits

AWS Managed Hosting Services And Dedicated Hosting Benefits


AWS Managed Hosting Services And Dedicated Hosting Benefits

Tej pandey

Oct 11, 2023

What is Serverless Security? Risk & Best Practices

What is Serverless Security? Risk & Best Practices

Serverless computing  is a rising topic right now in the cloud tech industry. As per a Datad...


What is Serverless Security? Risk & Best Practices

Anup Giri

Oct 11, 2023

Difference Between Cloud Computing and Cybersecurity

Difference Between Cloud Computing and Cybersecurity


Difference Between Cloud Computing and Cybersecurity

Mukesh Awasthi

Oct 11, 2023

DevOps for Developers: How It Helps Streamline the Development Process

DevOps for Developers: How It Helps Streamline the Development Process

As per a survey done by Puppet, firms with DevOps practice have increased recovery speeds by 24 ti...


DevOps for Developers: How It Helps Streamline the Development Process

Roshan Raman Giri

Oct 11, 2023

New AWS Announcements for August 2023

New AWS Announcements for August 2023


New AWS Announcements for August 2023

Rohan Jha

Oct 11, 2023

The FinOps Chronicles

The FinOps Chronicles


The FinOps Chronicles

Anup Giri

Oct 11, 2023

AWS Auto scale Instance-Based on RabbitMQ Custom Metrics

AWS Auto scale Instance-Based on RabbitMQ Custom Metrics


AWS Auto scale Instance-Based on RabbitMQ Custom Metrics

Anup Giri

Oct 11, 2023

Overcome Merge Hell with Trunk based development and Continuous Integration

Overcome Merge Hell with Trunk based development and Continuous Integration


Overcome Merge Hell with Trunk based development and Continuous Integration

Rohan Jha

Oct 11, 2023

What's the difference between CapEX Vs OpEX in Cloud Computing?

What's the difference between CapEX Vs OpEX in Cloud Computing?


What's the difference between CapEX Vs OpEX in Cloud Computing?

Tej pandey

Oct 11, 2023

How Does Your Organization Keep Cloud Costs Under Control?

How Does Your Organization Keep Cloud Costs Under Control?


How Does Your Organization Keep Cloud Costs Under Control?

Susmita Karki Chhetri

Oct 11, 2023

Microsoft Azure vs AWS vs Google Cloud Comparison

Microsoft Azure vs AWS vs Google Cloud Comparison


Microsoft Azure vs AWS vs Google Cloud Comparison

Mukesh Awasthi

Oct 11, 2023

What are the Benefits of Amazon S3 Glacier?

What are the Benefits of Amazon S3 Glacier?


What are the Benefits of Amazon S3 Glacier?

Anup Giri

Oct 11, 2023

Leverage Azure Migrate to Discover and Assess Your AWS Instances for Smooth Migration to Azure

Leverage Azure Migrate to Discover and Assess Your AWS Instances for Smooth Migration to Azure


Leverage Azure Migrate to Discover and Assess Your AWS Instances for Smooth Migration to Azure

Rohan Jha

Oct 11, 2023