How To Insert Into a DynamoDB Table with Boto3

Looking for an example of how to Insert a record into your DynamoDB Table using Python Boto3? This is the article for you.

Note that the full code is available at the bottom of this article.

Before you start, remember that you need proper IAM Permissions in order to interact with DynamoDB. For inserting, you require the dynamodb:PutItem permision. Make sure that the user or role you are using has this permission. If you don’t know how to create an IAM user/role with a policy, check out my YouTube tutorial here.

Also, if you’re looking to perform the Query operation on your table, check out my other article here.

First we need to import boto3, which is the Python SDK that allows us to interact with DynamoDB APIs.

import boto3

Next we need to get a reference to the DynamoDB resource using the below code snippet.

Note that we are using the DynamoDB resource and not the client object. The resource object offers higher level APIs which make it easier to access It is also the more modern way of interacting with Dynamo. However, resource may not always be completely up to date and you can alternatively use the client. The client offers more verbose lower level APIs. I personally suggest you use the resource object for all your interactions with Dynamo.

dynamodb = boto3.resource('dynamodb')

Next up we need to get a reference to our DynamoDB table using the following lines. Note that I am using a Lambda function (an AWS service) to interact with Dynamo. But you certainly don’t need to.

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

Now we can perform our insert operation.

Note that you may need to do some pre-processing of your data to get it ready for the insert. The neat part of using the resource object is that it will automatically convert your Python primitives into the correct corresponding DynamoDB types. For example, if you provide it with a python integer, it will automatically use the Number field as the type of DynamoDB. The same applies with Strings, Lists, Booleans, etc.

To perform the insert, we use the PutItem API as seen below:

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

Note that running this code multiple times will overwrite the record. If you’re just looking to update a field of an existing object you should use the UpdateItem API which I will have another article for.

After running the code above, you should see the record in your DynamoDB table as seen below.

After running the code, our DynamoDB table now shows the new record.

Before you’re done, you’ll want to examine the HTTP status code in the response object to ensure the operation was successful. We’re looking for a 200 OK status code. You can check for it by using the following code:

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

You may also want to print out the response object to take a look at some of its other properties. It contains interesting things such as the number of internal retries dynamo performed (if required) and the requestId.

And here’s the full code putting all these snippets together:

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)
    

Thanks for reading and hope this helps!

Total
0
Shares
Leave a Reply

Your email address will not be published.

Related Posts