Garth Turner
Garth Turner

Reputation: 25

Use Shopify API with Google Sheet FetchUrl App

Sorry i am a bit naive - learning as i go. I am trying to post data to my shopify store using their API. https://shopify.dev/docs/admin-api/rest/reference/inventory/inventorylevel The syntax (According to Shopify website) is: POST /admin/api/2020-04/inventory_levels/set.json { "location_id": xxxxxxx, "inventory_item_id": xxxxxxx, "available": xx }

I have succesfully used GET with the API to fetch information. Buty until now i have used URLS without thes payload data. I am now tryiong to add that payload to my script - see below, and its not working:

This is the script:

function myfunction() {  
var url = "https://<myshopname>.myshopify.com/admin/api/2020-04/inventory_levels/set.json";
var payloaddata = {
  "location_id": <mylocationid>,
  "inventory_item_id": <inventoryitemid>,
  "available": <quantity to update>
  };
var payload = JSON.stringify(payloaddata);
var username = "<key>";
var password = "<password>";

  var response = UrlFetchApp.fetch(url, {"method":"PUT","headers": {"Authorization": "Basic " + Utilities.base64Encode(username + ":" + password)},payload:payload});

Logger.log(response.getContentText());
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
}

The response code is 406 , which is (according to Shopify) means:

The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request."

Sorry - its probably some really simple syntax error - but i am just learning.

Upvotes: 0

Views: 1186

Answers (1)

Bilal Akbar
Bilal Akbar

Reputation: 4930

There are 2 minor problems with your code.

  • HTTP Method
  • Content Type

As per Shopify Documentation for Inventory API, Set Inventory level is a POST request.

Besides that Shopify expects ContentType to be application/json while skipping it uses default value in your case that is application/x-www-form-urlencoded as per Google Apps Script Docs. Changing this, your code would look like

function myfunction() {
    var url = "https://<myshopname>.myshopify.com/admin/api/2020-04/inventory_levels/set.json";
    var payloaddata = {
        "location_id": <mylocationid>,
        "inventory_item_id": <inventoryitemid>,
        "available": <quantity to update>
      };

    var payload = JSON.stringify(payloaddata);
    var username = "<key>";
    var password = "<password>";

    var response = UrlFetchApp.fetch(url, {
        method: "POST",
        payload: payload,
        contentType: "application/json",
        headers: { "Authorization": "Basic " + Utilities.base64Encode(username + ":" + password) }
    });

    Logger.log(response.getContentText());
    var json = response.getContentText();
    var data = JSON.parse(json);
    Logger.log(data);
}

Upvotes: 1

Related Questions