pythonamazon-web-servicesamazon-dynamodb

DynamoDB Python API: Way to check result of conditional expression?


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?


Solution

  • 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')