We will create a Lambda function that deletes all items with the specified partition key and sort key in the DynamoDB table. It also deletes the image file in the S3 bucket:
Open AWS Lambda console, click Create function

Enter function name, e.g., book_delete

Copy the following code and paste to lambda_function.py
import boto3
import json
import os
from boto3.dynamodb.conditions import Key
# AWS clients
dynamodb = boto3.resource("dynamodb")
s3 = boto3.client("s3")
# ENV
TABLE_NAME = "Books"
RESIZE_BUCKET = os.environ.get(
"RESIZE_BUCKET",
"book-image-resize-stores-tranvix"
)
table = dynamodb.Table(TABLE_NAME)
def get_image_name(image_url: str) -> str:
"""
Extract file name from S3 URL
"""
return image_url.split("/")[-1]
def lambda_handler(event, context):
try:
# ========= 1. Get book id from path =========
book_id = event["pathParameters"]["id"]
# ========= 2. Get book item (rv_id = 0) =========
book_resp = table.get_item(
Key={
"id": book_id,
"rv_id": 0
}
)
if "Item" not in book_resp:
return {
"statusCode": 404,
"body": json.dumps({"message": "Book not found"})
}
image_url = book_resp["Item"].get("image")
image_name = get_image_name(image_url) if image_url else None
# ========= 3. Query ALL items of this book =========
query_resp = table.query(
KeyConditionExpression=Key("id").eq(book_id)
)
items = query_resp["Items"]
# ========= 4. Batch delete DynamoDB items =========
with table.batch_writer() as batch:
for item in items:
batch.delete_item(
Key={
"id": item["id"],
"rv_id": item["rv_id"]
}
)
# ========= 5. Delete image from S3 resize bucket =========
if image_name:
s3.delete_object(
Bucket=RESIZE_BUCKET,
Key=image_name
)
return {
"statusCode": 200,
"body": json.dumps({"message": "Book deleted successfully"}),
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "DELETE,OPTIONS",
"Access-Control-Allow-Headers": "Content-Type,Authorization"
}
}
except Exception as e:
print("ERROR:", str(e))
return {
"statusCode": 500,
"body": json.dumps({"message": "Delete book failed"}),
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
}
}

Function deployed successfully

Configure environment variables for Lambda function

Add the following environment variable:
book-image-resize-stores-tranvix)
Confirm environment variable is updated successfully

Grant function permission to read and delete data from DynamoDB and delete objects in S3 bucket

On the IAM Role page, click Add permissions > Create inline policy

Select JSON tab and add the following policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:Query",
"dynamodb:DeleteItem",
"dynamodb:BatchWriteItem"
],
"Resource": "arn:aws:dynamodb:AWS_REGION:ACCOUNT_ID:table/Books"
},
{
"Effect": "Allow",
"Action": "s3:DeleteObject",
"Resource": "arn:aws:s3:::YOUR_BUCKET_NAME/*"
}
]
}

Enter policy name, e.g., LambdaBooksDeletePolicy

Policy created successfully and attached to role
