Varun Shridhar
Varun Shridhar

Reputation: 153

How do I create a Presigned URL to download a file from an S3 Bucket using Boto3?

I have to download a file from my S3 bucket onto my server for some processing. The bucket does not support direct connections and has to use a Pre-Signed URL.


The Boto3 Docs talk about using a presigned URL to upload but do not mention the same for download.

Upvotes: 7

Views: 30725

Answers (2)

Just to add to John's answer above, and save time to anyone poking around, the documentation does mention how to download as well as upload using the presigned URL as well:

How to download a file:

import requests    # To install: pip install requests

url = create_presigned_url('BUCKET_NAME', 'OBJECT_NAME')
if url is not None:
    response = requests.get(url)

Python Presigned URLs documentation: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html

Upvotes: 0

John Rotenstein
John Rotenstein

Reputation: 269091

import boto3

s3_client = boto3.client('s3')

BUCKET = 'my-bucket'
OBJECT = 'foo.jpg'

url = s3_client.generate_presigned_url(
    'get_object',
    Params={'Bucket': BUCKET, 'Key': OBJECT},
    ExpiresIn=300)

print(url)

For another example, see: Presigned URLs — Boto 3 documentation

You can also generate a pre-signed URL using the AWS CLI:

aws s3 presign s3://my-bucket/foo.jpg --expires-in 300

See: presign — AWS CLI Command Reference

Upvotes: 18

Related Questions