3

Using DynamoDB, I know I can specify a conditional expression to control updates, for example, using attribute_not_exists() to prevent overwriting an existing item. However, is there any way to check the result of this? I.e. if there was indeed an existing item and the create failed, I'd like to know that so I can return an error code in my HTTP response. However, looking at the documentation in Boto3, by default put_item returns nothing, so I'm unsure of how I'd be able to monitor the success of the operation. Anyone found a way to do this?

2 Answers 2

4

To provide a code example

import boto3
from botocore.exceptions import ClientError

dynamodb = boto3.client('dynamodb')

try:
    response = dynamodb.put_item(
        TableName='my-table',
        Item={
            "MyPartitionKey": {
                "S": 'some-unique-value'
            }
        },
        ConditionExpression="attribute_not_exists(MyPartitionKey)",
    )
    print('this worked!')
except ClientError as e:
    if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
        print('This was not a unique key')
    else:
        print('some other dynamodb related error')
Sign up to request clarification or add additional context in comments.

Comments

2

Found it, ConditionalCheckFailedException is thrown. Disappointed the docs don't mention this, other kinds of exceptions are detailed in the boto3 docs, but not this one!

1 Comment

Agreed that this should be better documented. I learned this from this SO answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.