Search code examples
google-apps-scriptgoogle-content-api

Specify the API version using an Advanced Service within Google Apps Scripts?


I need to use version 2.1 of the Content API within my script however, I'm unsure how to pass the version number.

Here's the relevant part of the code:

var products = ShoppingContent.Products.list(merchantId, {
    pageToken: pageToken,
    maxResults: maxResults,
    includeInvalidInsertedItems: true
});

I've tried passing version: 2.1 but no cigar.

Thanks


Solution

  • The version for a particular client library is specified only when you are enabling a particular advanced service. Not all versions are supported by all client libraries e.g. the Drive advanced service does not support the v3 endpoints.

    For the ShoppingContent client library, Apps Script provides bindings only to version 2:

    enter image description here

    Thus, to use v2.1, you will need to treat the Shopping Content API as an external API, and access it using UrlFetchApp. You will need to authorize the requests as appropriate, constructing your own OAuth2 authorization header with the ScriptApp.getOAuthToken() method, e.g.:

    function addAuthHeader(headers) {
      var token = ScriptApp.getOAuthToken();
      headers['Authorization'] = 'Bearer ' + token;
    }
    function getBaseURI(version) {
      return 'https://www.googleapis.com/content/' + version + '/';
    }
    
    function listProducts(merchantId, pageToken) {
      const base = getBaseURI('v2.1');
      const path = merchantId + '/products';
      if (pageToken)
        path + '?pageToken=' + pageToken;
    
      const headers = {
        /* whatever you need here */
      };
      addAuthHeader(headers);
    
      const fetchOptions = {
        method: 'GET',
        /* whatever else you need here
          https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetchurl-params
         */
        headers: headers
      };
      var pageResponse = UrlFetchApp.fetch(base + path, fetchOptions);
      var onePageOfResults = JSON.parse(pageResponse.getContentText());
      /* whatever else */
    }