How to update product info using C# RestClient?

dvanmaanendvanmaanen Posts: 4Member
Can someone give me an example of how to 'PUT' changes to product info using C# RestClient?

Thanks,

Daan

7 comments

  • gregaricangregarican Posts: 248Member 
    edited December 2018
    Here is something that should work. I haven't tested the code, and basically just changed the API URL and JSON, since my code works off the LS Retail API and not the LS Ecom API.

    Hope this helps!

    var url = @"https://ApiKey:[email protected]/en/products/ProductId.json";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "PUT";
    request.Credentials = new NetworkCredential(shopifyApiKey, shopifyApiPwd);
    request.PreAuthenticate = true;
    request.ContentType = "application/json";
    
    var json = @{
      \product\": {
        \"visibility\": \"hidden\",
        \"data01\": \"\",
        \"data02\": \"\",
        \"data03\": \"\",
        \"title\": \"Wade Crewneck Navyblue\",
        \"fulltitle\": \"Wade Crewneck Navyblue\",
        \"description\": \"De Wade Crewneck Navyblue van Wemoto. Deze blauwe trui met de enorme W op de chest heeft een heel klassieke look.\",
        \"content\": \"De Wade Crewneck Navyblue van Wemoto. Deze blauwe trui met de enorme W op de chest heeft een heel klassieke look.\",
        \"deliverydate\": 1,
        \"supplier\": 2,
        \"brand\": 3
      }
    }";
    
    using (var writer = new StreamWriter(request.GetRequestStream()))
    {
    	writer.Write(json);
            writer.Flush();
            writer.Close();
    }
    
    var response = new HttpResponseMessage();
    
    using (var responseApi = (HttpWebResponse)request.GetResponse())
    {
    	using (var reader = new StreamReader(responseApi.GetResponseStream()))
            {
            	var objText = reader.ReadToEnd();
                    var objJson = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(objText);
                    response.Content = new StringContent(objText);
            }
    }
    
    // Do whatever you want with the HttpWebResponse...
    

    The code formatting is kinda screwed up posting this, but you get the idea :smiley:
    Post edited by jamesratcliffe on
  • jamesratcliffejamesratcliffe Posts: 160Administrator, Lightspeed Staff moderator
    @gregarican I think you're missing an opening double-quote on line 8.
    James Ratcliffe
    Lightspeed HQ
  • gregaricangregarican Posts: 248Member 
    It's missing a lot, since the text didn't retain everything when pasted into the posting :smiley:
  • jamesratcliffejamesratcliffe Posts: 160Administrator, Lightspeed Staff moderator
    Oh yeah, I can see it when I edit the comment. That's bizarre.
    James Ratcliffe
    Lightspeed HQ
  • dvanmaanendvanmaanen Posts: 4Member
    This code gives me an error on the line that says:
    using (var webResponse = (HttpWebResponse)request.GetResponse())
    400 - invalid command.


    I have now this:

    public void Test(LsProduct lsProduct)
    {
        var url = $@https://{ApiKey}:{ApiSecret}@api.shoplightspeed.com/us/products/{lsProduct.Id}.json";
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "PUT";
        request.Credentials = new NetworkCredential(ApiKey, ApiSecret);
        request.PreAuthenticate = true;
        request.ContentType = "application/json";

        var json = new JavaScriptSerializer().Serialize(lsProduct);

        using (var writer = new StreamWriter(request.GetRequestStream()))
        {
            writer.Write(json);
            writer.Flush();
            writer.Close();
        }

        var responseMessage = new HttpResponseMessage();

        using (var webResponse = (HttpWebResponse)request.GetResponse())
        {
            var stream = webResponse.GetResponseStream();
            if (stream == null) return;

            using (var reader = new StreamReader(stream))
            {
                var objText = reader.ReadToEnd();
                var objJson = (JObject)JsonConvert.DeserializeObject(objText);
                responseMessage.Content = new StringContent(objText);
            }

        }
    }


    Before digging into this, if it is possible I would like to use the RestSharp.RestClient object, because I have got that working for reading data from LightSpeed and I can re-use the object.

    For reading I have this, which works like a charm:

    private async Task<LsProduct> GetLsProduct(int lsProductId)
    {
        var request = new RestRequest($"products/{lsProductId}.json", Method.GET);
        var response = await _restClient.ExecuteGetTaskAsync(request);

        return ResponseToLsProduct(response);
    }

    private static LsProduct ResponseToLsProduct(IRestResponse response)
    {
        if (!response.IsSuccessful || response.Content.Length == 0) return null;

        var jObject = JObject.Parse(response.Content);
        if (jObject.Count == 0) return null;
        var jsonProduct = jObject["product"];

        return JsonConvert.DeserializeObject<LsProduct>(jsonProduct.ToString());
    }


    I tried to create an update method like this:

    public async Task UpdateLsProduct(LsProduct lsProduct)
    {
        var request = new RestRequest
        {
            Resource = $"products/{lsProduct.Id}.json",
            Method = Method.PUT
        };

        request.AddJsonBody(lsProduct);

        var response = await _restClient.ExecuteGetTaskAsync(request);
    }


    results:
    response.StatusCode: OK
    response.ResponseStatus: Completed
    BUT
    response.Content contains (in json) the unchanged object and the product in the shop remains unchanged.
    What am I doing wrong?
  • dvanmaanendvanmaanen Posts: 4Member
    edited December 2018

    I tried the above. It ends up with an error 400: invalid command.
    This happens while executing the line that says:

    using (var webResponse = (HttpWebResponse)request.GetResponse())
    

    This is what I have now:

    public void Test(LsProduct lsProduct)
    {
        var url = $"https://{ApiKey}:{ApiSecret}@api.shoplightspeed.com/us/products/{lsProduct.Id}.json";
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "PUT";
        request.Credentials = new NetworkCredential(ApiKey, ApiSecret);
        request.PreAuthenticate = true;
        request.ContentType = "application/json";
        
        const string json = "\"product\":{\"title\":\"test\"}";
     
        using (var writer = new StreamWriter(request.GetRequestStream()))
        {
            writer.Write(json);
            writer.Flush();
            writer.Close();
        }
     
        var responseMessage = new HttpResponseMessage();
     
        using (var webResponse = (HttpWebResponse)request.GetResponse())
        {
            var stream = webResponse.GetResponseStream();
            if (stream == null) return;
     
            using (var reader = new StreamReader(stream))
            {
                var objText = reader.ReadToEnd();
                var objJson = (JObject)JsonConvert.DeserializeObject(objText);
                responseMessage.Content = new StringContent(objText);
            }
        }
    }
    Post edited by dvanmaanen on
  • dvanmaanendvanmaanen Posts: 4Member
    That works. Thanks.
Sign In or Register to comment.