How to force delete_item using Python (boto3) to return an error when an item does not exist in DynamoDB?

Viewed 4186

By default delete_item from boto3 does not return an error even if operation is performed on an Item that does not exists.

id = '123'
timenow = '1589046426'

dynamodb = boto3.resource('dynamodb')
boto3_table = dynamodb.Table(MY_TABLE)
response = boto3_table.delete_item(Key={"ID": id, "TIMENOW": timenow})

How do I change the code above to force the delete_item to return an error when item does not exist?

3 Answers

One way would be to do a conditional delete using a condition-expression on the your partition key attribute name:

response = table.delete_item(
    Key={
        'pk': "jim.bob",
        "sk": "metadata"
    },
    ConditionExpression="attribute_exists (pk)",
)

If the item exists with this key AND the attribute that is the partition key exists on that key, it deletes the item. If the item does not exist, then you get:

The conditional request failed

If anyone has the same problem, here is the solution:

response = boto3_table.delete_item(Key={"IDID": idid, "TIMENOW": timenow},
           ConditionExpression="attribute_exists(ID) AND attribute_exists(TIMENOW)")

The ConditionExpression parameter with attribute_exists will only delete if the ID and TIMENOW are present in the record.

Another approach would be to use ReturnValues='ALL_OLD' which returns attributes associated with a given key if they existed prior removal:

response = boto3_table.delete_item(Key={"ID": id, "TIMENOW": timenow}, ReturnValues='ALL_OLD')
if not res['Attributes']:
  raise KeyError('Item not found!')
Related