how to put an Item in aws DynamoDb using aws Lambda with python

PythonPython 2.7Aws LambdaAmazon Dynamodb

Python Problem Overview


Using python in AWS Lambda, how do I put/get an item from a DynamoDB table?

In Node.js this would be something like:

dynamodb.getItem({
    "Key": {"fruitName" : 'banana'},
    "TableName": "fruitSalad"
}, function(err, data) {
    if (err) {
        context.fail('Incorrect username or password');
    } else {
        context.succeed('yay it works');
    }
});

All I need is the python equivalent.

Python Solutions


Solution 1 - Python

Using Boto3 (Latest AWS SDK for python)

You import it with

import boto3

Then call the client via

dynamodb = boto3.client('dynamodb')

Get item example

dynamodb.get_item(TableName='fruitSalad', Key={'fruitName':{'S':'Banana'}})

Put item example

dynamodb.put_item(TableName='fruitSalad', Item={'fruitName':{'S':'Banana'},'key2':{'N':'value2'}})

'S' indicates a String value, 'N' is a numeric value

For other data types refer http://boto3.readthedocs.org/en/latest/reference/services/dynamodb.html#DynamoDB.Client.put_item

Solution 2 - Python

Using latest AWS SDK

import boto3

def lambda_handler(event, context):
    # this will create dynamodb resource object and
    # here dynamodb is resource name
    client = boto3.resource('dynamodb')

    # this will search for dynamoDB table 
    # your table name may be different
    table = client.Table("dynamoDB")
    print(table.table_status)

    table.put_item(Item= {'id': '34','company':  'microsoft'})

If your are using AWS you can use this code sample, only you have to give permissions to this lambda function, you can find details in link

Solution 3 - Python

full example:

import boto3

def lambda_handler(event, context):

    client = boto3.client('dynamodb')
    
    for record in event['Records']:
        # your logic here...
        try:
            client.update_item(TableName='dynamo_table_name', Key={'hash_key':{'N':'value'}}, AttributeUpdates={"some_key":{"Action":"PUT","Value":{"N":'value'}}}) 
        except Exception, e:
            print (e)

please note that you need to decide when to use 'update_item' or 'put_item'.

with 'update_item' you ensure to have only one record with the same hash/range. if the record exists it can update this record, else it will create it

http://boto3.readthedocs.org/en/latest/reference/services/dynamodb.html#DynamoDB.Client.update_item

Solution 4 - Python

You can use below lines to write and read from the DynamoDB Table:

First, import the boto3 package

import boto3

Create an object for dynamoDB

dynamodb = boto3.resource('dynamodb')

Select your specific table

table = dynamodb.Table("fruitSalad")

Write:

table.put_item(Item= {'fruitName': 'Banana'})

Read:

table.get_item(Key={'fruitName': 'Banana'})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJordanView Question on Stackoverflow
Solution 1 - PythonomuthuView Answer on Stackoverflow
Solution 2 - Pythonsudhanshu allurwarView Answer on Stackoverflow
Solution 3 - PythonEyal ChView Answer on Stackoverflow
Solution 4 - PythonAmit TidkeView Answer on Stackoverflow