cancel
Showing results for 
Search instead for 
Did you mean: 

C# Updating a product Magento 2 API REST

Highlighted

C# Updating a product Magento 2 API REST

Hello i am trying to update a product in a magento store using the API REST, my version of Magento is 2.1.8

To do the test firstly i get the token, secondly i get an existing item by SKU, then send the same item to update with the smae values.

 

i have my code setup this way

 

Main.cs

 

namespace ConsoleApplicationMagento
{
    class Program
    {
        static void Main(string[] args)
        {
            Magento magento = new Magento("http://192.168.0.226:86");
            string token = magento.GetAdminToken("grupototal", "opxvMjLAlD48heuWg==").Trim('"');
            Product product = magento.GetProdcutBySku(token, "RFH1188PRZJ0UN-DR");
            magento.UpdateProdcutBySku(product, token);
        }
    }
}

Magento.cs

using Newtonsoft.Json;
using RestSharp;

namespace ConsoleApplicationMagento
{
    internal class Magento
    {
        private RestClient Client { get; set; }

        public Magento(string magentoUrl)
        {
            Client = new RestClient(magentoUrl);
        }

        public Magento(string magentoUrl, string token)
        {
            Client = new RestClient(magentoUrl);
        }

        public string GetAdminToken(string userName, string passWord)
        {
            var request = CreateRequest("/rest/V1/integration/admin/token", Method.POST);
            var user = new Credentials();
            user.username = userName;
            user.password = passWord;

            string json = JsonConvert.SerializeObject(user, Formatting.Indented);

            request.AddParameter("application/json", json, ParameterType.RequestBody);

            var response = Client.Execute(request);
            if(response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return response.Content;
            }
            else
            {
                return "";
                            }
        }

        public RestRequest CreateRequest(string endPoint, Method method)
        {
            var request = new RestRequest(endPoint, method);
            request.RequestFormat = DataFormat.Json;
            return request;
        }

        public Product GetProdcutBySku(string token, string sku)
        {
            var request = CreateRequest("/rest/V1/products/" + sku, Method.GET, token);

            var response = Client.Execute(request);

            if(response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Product product = JsonConvert.DeserializeObject<Product>(response.Content);
                return product;
            }

            return null;
        }

        public RestRequest CreateRequest(string endPoint, Method method, string token)
        {
            var request = new RestRequest(endPoint, method);
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Authorization", "Bearer " + token);
            request.AddHeader("Accept", "application/json");
            return request;
        }


        public bool UpdateProdcutBySku(Product product, string token)
        {
            var request = CreateRequest("/rest/V1/products/" + product.sku, Method.PUT, token);
            string json = JsonConvert.SerializeObject(product, Formatting.Indented);
            json = "{\"product\":" + json + ",\"saveOptions\": true}";
            request.AddParameter("application/json", json, ParameterType.RequestBody);
            var result = Client.Execute(request);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return true;
            }
            else
            {
                return false;
            }
        }  
    }
}

I am getting bad request saying the "cost" value must be set

But i am using the json struture from here to do UPDATE an i cant find any field called COST

https://magento.redoc.ly/2.3.5-admin/tag/productssku

My update json text

{"product":{
  "id": 59,
  "sku": "RFH1188PRZJ0UN-DR",
  "name": "Zapato casual de estrellas dorado",
  "attribute_set_id": 4,
  "price": 2000,
  "status": 1,
  "visibility": 1,
  "type_id": "simple",
  "created_at": "2018-06-18 21:31:40",
  "updated_at": "2018-06-28 19:51:19",
  "weight": 1,
  "extension_attributes": {
    "stock_item": {
      "item_id": 59,
      "product_id": 59,
      "stock_id": 1,
      "qty": 1000,
      "is_in_stock": true,
      "is_qty_decimal": false,
      "show_default_notification_message": false,
      "use_config_min_qty": true,
      "min_qty": 0,
      "use_config_min_sale_qty": 1,
      "min_sale_qty": 1,
      "use_config_max_sale_qty": true,
      "max_sale_qty": 10000,
      "use_config_backorders": true,
      "backorders": 0,
      "use_config_notify_stock_qty": true,
      "notify_stock_qty": 1,
      "use_config_qty_increments": true,
      "qty_increments": 0,
      "use_config_enable_qty_inc": true,
      "enable_qty_increments": false,
      "use_config_manage_stock": true,
      "manage_stock": true,
      "low_stock_date": null,
      "is_decimal_divided": false,
      "stock_status_changed_auto": 0
    }
  },
  "product_links": [],
  "options": [],
  "media_gallery_entries": [
    {
      "id": 224,
      "media_type": "image",
      "label": "Zapato casual de estrellas dorado",
      "position": 1,
      "disabled": false,
      "types": [
        "image",
        "small_image",
        "thumbnail"
      ],
      "file": "/r/f/rfh1188pr_estrellas_doradas_lateral.jpg"
    },
    {
      "id": 225,
      "media_type": "image",
      "label": "",
      "position": 2,
      "disabled": false,
      "types": [],
      "file": "/e/s/estrellas_plateadas_doradas_frontal.jpg"
    }
  ],
  "tier_prices": [],
  "custom_attributes": [
    {
      "attribute_code": "description",
      "value": "Zapato casual unicolor con estrellas y trenzas"
    },
    {
      "attribute_code": "short_description",
      "value": "Zapato casual unicolor con estrellas y trenzas"
    },
    {
      "attribute_code": "meta_title",
      "value": "Zapato casual de estrellas dorado"
    },
    {
      "attribute_code": "meta_keyword",
      "value": "Zapato, Estilo, Genero, Casual"
    },
    {
      "attribute_code": "meta_description",
      "value": "Zapato casual unicolor con estrellas y trenzas"
    },
    {
      "attribute_code": "image",
      "value": "/r/f/rfh1188pr_estrellas_doradas_lateral.jpg"
    },
    {
      "attribute_code": "small_image",
      "value": "/r/f/rfh1188pr_estrellas_doradas_lateral.jpg"
    },
    {
      "attribute_code": "thumbnail",
      "value": "/r/f/rfh1188pr_estrellas_doradas_lateral.jpg"
    },
    {
      "attribute_code": "color",
      "value": "18"
    },
    {
      "attribute_code": "category_ids",
      "value": [
        "3",
        "4",
        "11",
        "27"
      ]
    },
    {
      "attribute_code": "options_container",
      "value": "container2"
    },
    {
      "attribute_code": "required_options",
      "value": "0"
    },
    {
      "attribute_code": "has_options",
      "value": "0"
    },
    {
      "attribute_code": "image_label",
      "value": "Zapato casual de estrellas dorado"
    },
    {
      "attribute_code": "small_image_label",
      "value": "Zapato casual de estrellas dorado"
    },
    {
      "attribute_code": "thumbnail_label",
      "value": "Zapato casual de estrellas dorado"
    },
    {
      "attribute_code": "country_of_manufacture",
      "value": "CN"
    },
    {
      "attribute_code": "url_key",
      "value": "Zapato-casual-de-estrellas-dorado-2"
    },
    {
      "attribute_code": "msrp_display_actual_price_type",
      "value": "0"
    },
    {
      "attribute_code": "tax_class_id",
      "value": "2"
    },
    {
      "attribute_code": "marca",
      "value": "Refresh"
    },
    {
      "attribute_code": "modelo",
      "value": "RFH1188PR"
    }
  ]
},"saveOptions": true}

I will appreciate any advice, thank you