How to delete file from S3 using API

wlepczynski

Wojciech Lepczyński

Posted on March 16, 2023

How to delete file from S3 using API

I wanted to show, how you can delete data from S3 using API. With a simple curl, you can delete files from S3. In the following example, I delete the test_empty.txt file from the bucket named BUCKET_NAME from the eu-west-1 region. For correct operation, you must provide ADD_YOUR_KEY_ID and ADD_YOUR_SECRET_KEY_VALUE .

#!/usr/bin/env bash

access_key_id=ADD_YOUR_KEY_ID
secret_key=ADD_YOUR_SECRET_KEY_VALUE
file_path=test_empty.txt
bucket_name=BUCKET_NAME
region=eu-west-1



# metadata
content_Type="application/octet-stream"
date=`date -R`
full_path="/${bucket_name}/${file_path}"
signature_string="GET\n\n${content_Type}\n${date}\n${full_path}"
signature=`echo -en ${signature_string} | openssl sha1 -hmac ${secret_key} -binary | base64`

# save file in file_path ( -o, --output <file>)(-s, --silent)(-S disable progress meter but still show error messages)
curl -Sso ${file_path} \
  -H "Host: ${bucket_name}.s3.${region}.amazonaws.com" \
  -H "Date: ${date}" \
  -H "Content-Type: ${content_Type}" \
  -H "Authorization: AWS ${access_key_id}:${signature}" \
  -X "GET" https://${bucket_name}.s3.${region}.amazonaws.com/${file_path}
Enter fullscreen mode Exit fullscreen mode

By making a small change, you can download the file first and then remove it from S3. More information can be found on my blog.

I also recorded a video on YouTube in which I show 7 ways to delete data from S3 - https://youtu.be/SckbCTULsHM

You'd rather read than watch, no problem. On my blog you will also find an article in which I described 7 ways to delete data from S3 - https://lepczynski.it/en/aws_en/7-ways-to-delete-data-from-s3/

💖 💪 🙅 🚩
wlepczynski
Wojciech Lepczyński

Posted on March 16, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related