70

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.

Timbus Calin
  • 13,809
  • 5
  • 41
  • 59
Jordan
  • 1,564
  • 2
  • 13
  • 32
  • late to this but i have written a similar code for DynamoDB basic operation that covers your question: https://github.com/hardikvasa/database-journal/blob/master/code-samples/dynamodb.py – hnvasa Jun 09 '19 at 21:01
  • @hnvasa : the question is using AWS lambda. – ashdnik Nov 07 '19 at 11:43
  • This video may help https://www.youtube.com/watch?v=neDCz0YsEj4 – Shams May 20 '21 at 10:22

4 Answers4

103

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

Nicolò Gasparini
  • 2,228
  • 2
  • 24
  • 53
omuthu
  • 5,948
  • 1
  • 27
  • 37
  • 30
    any idea how to convert an actual dict that you'd use in python into amazon's crazy structure? – ryantuck Jul 16 '16 at 23:34
  • 23
    RyanTuck if you use resource and table it is not necessary and you can use your dict. dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(TableName) table.put_item({"fruitName" : 'banana'}) – Leticia Santos Jun 09 '17 at 18:33
  • 3
    Ryan Tuck question is very legit. When you need to use attribute_not_exists ConditionExpression, it is only possible using the client and not the resource. So when using the client you have to deal with the stupid formatting of boto3 low level client .... – doanduyhai Dec 12 '17 at 20:15
  • Keep in mind that if you created a primary key with a secondary key associated, you need to query for both of them – Nicolò Gasparini Dec 11 '18 at 21:33
  • confused as to when I have to tell boto3, which is after all python, what the type of a parameter is. I have seen examples that do not that seem to work. – Samantha Atkins Jul 12 '19 at 21:50
  • [One or more parameter values were invalid: Type mismatch for key xyz expected: S actual: M](https://stackoverflow.com/q/57139203/495455) – Jeremy Thompson Apr 27 '23 at 13:47
47

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

  • 1
    this is an apt answer as I am facing issues with boto3.client. Also, additional formatting is required in client! – satish silveri Sep 29 '20 at 15:36
  • this is what I'm looking for, thanks. I'm running Dynamo using Docker on localhost:9999. After creating the table without exception, the `print(table.table_status)` statement returns `botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the DescribeTable operation: Cannot do operations on a non-existent table` – med Dec 06 '22 at 11:25
22

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

Eyal Ch
  • 9,552
  • 5
  • 44
  • 54
6

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'})
Amit Tidke
  • 81
  • 1
  • 3