Search code examples
google-apps-scriptgoogle-apigoogle-drive-apigoogle-api-js-client

Fetching a drive file image using Urlfetch App in GAS


I found a new way to access a dive image using the file ID. The image file is public shared for testing

https://lh3.google.com/u/0/d/1wJsovhXjWZM5qfyh3_VvJKODxw1DWQG_=w320-h200-k-iv1

This url would produce 302 and then render a browser image perfectly.

But When I run using a URLFetch it gives me error 400. That’s an error. Your client has issued a malformed or illegal request. That’s all we know.

I have tried with

function myFunction() {
    var response = UrlFetchApp.fetch("https://lh3.google.com/u/0/d/1wJsovhXjWZM5qfyh3_VvJKODxw1DWQG_=w320-h200-k-iv1", {
        'followRedirects': true,
        'muteHttpExceptions': true,
        'headers': {
            'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
        }
    })
    DriveApp.createFile(response.getBlob())
}

Solution

  • Two things

    1. If you fetch a publicly accessible URL, you do not need to authenticate. Just remove the following line:
            'headers': {
                'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
            }
    
    1. If you try to fetch the redirection URL https://lh3.google.com/u/0/d/1wJsovhXjWZM5qfyh3_VvJKODxw1DWQG_=w320-h200-k-iv1", you will get the following as result:

    enter image description here

    If you want to get the actual image instead, you need to fetch the actual URL of the image:

    function myFunction() {
      var response = UrlFetchApp.fetch("https://lh3.googleusercontent.com/fife/ABSRlIr3o6GAAI3eXS8cz1Z9bWEkLp-D6RhKP8NDUfH81qWSIVA9Jj2XYE5XRifQ1-PZAPKEeH9t-0eqPCY6u_mD87pZ_hsTM9atsTL6rpDW5uZQgWVXH-UHuEMZspXRnYeZdZ87r9KQ4_YeO7z55p7qBnJeerzOaP3K_qhbEjCGpx2Eb5ln6gpvgaxAdUdV5HhUtw5d821iiod8JFNWqfiq7uGK0mvLKqUl7ZKIskhYBYW7G7r1uz5H-7DAymiwFQtQ6d2dUrWRWmms0u7O7Q5TSJHXt2HxhibEpgsFxBAK17GAmOTUa3bii3VoGifUXlKlGU1QAKH_i5ttFZn_Bbak2RzivY6QC1uDG-LgirWMzTT-2zqZcIM115qSDzrfktDaryHxBhIrUVvhrlWJ5j3QaRfUHh3__HSDgkm_Xe7-QCD3PuEYOgjxAsaLQoD3tdCywfKBWAT0crHJtTFQxtWmwR5RwNeLbFrzoeCEvVhZcaaYupC6Hwrtz8WHExAMnDHojXhqXCAwNSVYVzFVnxiigbZvl6UbSqXYsBqm_DLYlftCZ7pr28pkCnn_gKkbqitzIb-ei0mnOPFjqmMCAstLTTh4H7buZrAVvZZeYRe8xl9ypkAal_0z81L7dx3qVzCtFn6JuCRSZnlIFVseDURpFL4vDB6jqXoaEmwXt-ajA9MxefprFo6ujAdjFr_sUzHboBCfz9r3hPhvO21Qb2R2rnKGEpDRUuXr7Q=w320-h200-k-ft", {
        'followRedirects': true,
        'muteHttpExceptions': true,
      })
      Logger.log(response.getResponseCode());
      DriveApp.createFile(response.getBlob().setName("blob from url"))
    }