Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-api

UrlFetchApp works in script editor, not in document


I have a Google Apps script for Sheets which makes a request to the Google Books API to look up ISBN by title/author, and the requests reliably work when testing in the script editor, but when I test it with the same data in the spreadsheet itself, it fails with this error:

Request failed for https://www.googleapis.com/books/v1/volumes?q=Deedy%2C%20Carmen%20Agra%2014%20Cows%20for%20America returned code 403. Truncated server response: { "error": { "errors": [ { "domain": "global", "reason": "unknownLocation",
 "message": "Cannot determine user location for geogra... (use muteHttpExceptions option to examine full response) (line 55).

This is the execution transcript for the same function being run in the script editor with the same data, successfully:

[16-08-05 14:39:09:772 EDT] Starting execution
[16-08-05 14:39:10:558 EDT] UrlFetchApp.fetch([https://www.googleapis.com/books/v1/volumes?q=Deedy%2C%20Carmen%20Agra%2014%20Cows%20for%20America]) [0.778 seconds]
[16-08-05 14:39:10:559 EDT] HTTPResponse.getResponseCode() [0 seconds]
[16-08-05 14:39:10:559 EDT] HTTPResponse.getContentText() [0 seconds]
[16-08-05 14:39:10:569 EDT] Logger.log([found title match for '%s': '%s', [14 Cows for America, 14 Cows for America]]) [0 seconds]
[16-08-05 14:39:10:583 EDT] Logger.log([result: %s, [9781561454907]]) [0 seconds]
[16-08-05 14:39:10:584 EDT] Execution succeeded [0.804 seconds total runtime]

I've made the source code available if it's relevant.


Solution

  • The URL Fetch service uses Google's network infrastructure for efficiency and scaling purposes.

    And "Google Books API results are restricted based on your server or client application's IP address" (doc). And for some reason it can't determine the server's location where Google Apps Scripts are running and returns the error Cannot determine user location for geographically restricted operation. You can try sending the parameter country, just change this line:

    var isbnEndpoint = "https://www.googleapis.com/books/v1/volumes?q=";
    

    to this:

    var isbnEndpoint = "https://www.googleapis.com/books/v1/volumes?country=US&q=";