Ad

Shopify Api Updating Variants Returned Error

- 1 answer

I wanted to update the inventory_quantity of the store products and I've got error saying

The remote server returned an error: (400) Bad Request.

This is how I implement it.

ProductVariant product = new ProductVariant();
product.id = 1962693211;
product.inventory_quantity = 20;
product.inventory_management = "shopify";

string ordersApi = ConfigurationManager.AppSettings["Shopify_Api_Inventory"];
string url = ordersApi.Replace("{StoreName}", _cred.StoreName);
url = url.Replace("{id}", product.id.ToString());
string xmlStringResult = string.Empty;


try
{
    var req = (HttpWebRequest)WebRequest.Create(url);
    req.Method = "PUT";
    req.ContentType = "application/json";
    req.Credentials = GetCredential(url);
    req.PreAuthenticate = true;

    var json = JsonConvert.SerializeObject(product);
    json = "{ variant: " + json + "}";



    if (!String.IsNullOrEmpty(json))
    {
        using (var ms = new MemoryStream())
        {
            using (var writer = new StreamWriter(req.GetRequestStream()))
            {
                writer.Write(json);
                writer.Close();
            }
        }
    }

    using (var resp = (HttpWebResponse)req.GetResponse())
    {
        if (resp.StatusCode != HttpStatusCode.OK)
        {
            string message = String.Format("Call failed. Received HTTP {0}", resp.StatusCode);
            AppendLog(string.Format("Error: {0}", message));
            return xmlStringResult;
        }

        var sr = new StreamReader(resp.GetResponseStream());
        xmlStringResult = sr.ReadToEnd();
    }
}
catch (Exception ex)
{
    AppendLog(string.Format("Error: {0}", ex.Message));
}

Thank you in advance for the help.

Ad

Answer

This line of code

json = "{ variant: " + json + "}";

produces the below json

{ variant: {"id":1962693211,"inventory_quantity":20,"inventory_management":"shopify"}}

which is invalid. The valid json should be

{ "variant": {"id":1962693211,"inventory_quantity":20,"inventory_management":"shopify"}}

so you need to change the above line of code to this

json = "{ \"variant\": " + json + "}";
Ad
source: stackoverflow.com
Ad