Search code examples
pythongoogle-cloud-platformgoogle-cloud-storagegoogle-api-client

Google Cloud Platform: How can I get a signed URL for putting an object to Google Cloud Store with Python


I'm using google-api-python-client but can't make any progress in how to create signed PUT URL just for direct uploading object to Google Cloud Storage Bucket. There is no consistent documentation on how I can get signed URL using the last version of the Google Python client.


Solution

  • I used the google cloud storage library. I recommend it as its supported by google and abstracts some of the complexities in the signed url dance

    First get a certificate https://console.developers.google.com/

    Save the certificate to your project

    Install google cloud library

    pip install google-cloud-storage==1.9.0
    

    Import generate_signed_url and google.storage and then initialize storage client with the certificate and access the bucket

    from google.cloud.storage._signing import generate_signed_url
    from google.cloud import storage
    
    client = storage.Client.from_service_account_json('path/to/certificate.json')
    
    expiration = datetime.datetime.now() + datetime.timedelta(days=1)
    API_ACCESS_ENDPOINT = 'https://storage.googleapis.com'
    canonical_resource = bucketpath + "resource.jpeg"
    
    url = generate_signed_url(
        client._credentials, resource=canonical_resource,
        api_access_endpoint=API_ACCESS_ENDPOINT,
        expiration=expiration, method="PUT",
        content_type="jpeg"
    )
    print(url)
    

    full documentation https://googleapis.github.io/google-cloud-python/latest/storage/client.html