magento2magento2.2magento-rest-api

magento api 2 create product error


i have used C# to call magento rest api to create a new product (magento version 2.2.5)

this is the body data:

{
  "product": {
  "id": 0,
  "sku": "MS-Champ11",
  "name": "Champ Tee11",
  "attribute_set_id": 9,
  "price": 110,
  "status": 1,
  "visibility": 4,
  "type_id": "simple",
  "created_at": null,
  "updated_at": null,
  "weight": 5,
  "extension_attributes": null,
  "product_links": null,
  "options": null,
  "media_gallery_entries": null,
  "tier_prices": null,
  "custom_attributes": [
      {
        "attribute_code": "description",
        "value": "Test Description"
      }
    ]
  },
  "save_options": false
}

this is my C# code:

public string CreateProduct(Product product)
    {
        try
        {
            var request = CreateRequest("/rest/V1/products", Method.POST, Token);
            var prod = new ProductModel();
            prod.Product = product;
            string json = JsonConvert.SerializeObject(prod, Formatting.Indented);
            request.AddParameter("application/json", json, ParameterType.RequestBody);

            var response = Client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return "Succeed";
            }
            else
            {
                return "Failed";
            }
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

I tried many time but it was always responding error

"BadRequest"

{"message":"Invalid product data: %1","parameters":["Invalid attribute set entity type"]}

what was i doing wrong? please help


Solution

  • In your body data following data is incorrect

    "attribute_set_id": 9,
    

    You can find attribute set id in Magento admin -> Stores -> Attribute Set -> 'Your attribute set'. You can find id value in url

    magento.domain/admin/catalog/product_set/edit/id/4/key