Search code examples
amazon-web-servicesamazon-s3botoboto3

Generate Signed URL in S3 using boto3


In Boto, I used to generate a signed URL using the below function.

import boto
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name, validate=True)
key = bucket.get_key(key)
signed_url = key.generate_url(expires_in=3600)

How do I do the exact same thing in boto3?
I searched through boto3 GitHub codebase but could not find a single reference to generate_url.
Has the function name changed?


Solution

  • From Generating Presigned URLs:

    import boto3
    import requests
    from botocore import client
    
    
    # Get the service client.
    s3 = boto3.client('s3', config=client.Config(signature_version='s3v4'))
    
    # Generate the URL to get 'key-name' from 'bucket-name'
    url = s3.generate_presigned_url(
        ClientMethod='get_object',
        Params={
            'Bucket': 'bucket-name',
            'Key': 'key-name'
        },
        ExpiresIn=3600 # one hour in seconds, increase if needed
    )
    
    # Use the URL to perform the GET operation. You can use any method you like
    # to send the GET, but we will use requests here to keep things simple.
    response = requests.get(url)
    

    Function reference: generate_presigned_url()