Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

Magento 2 API Create Simple Products

Vinh Jacker | 12-18-2024

Magento 2 API Create Simple Products

Efficiency and precision are key to managing an online store in eCommerce. Magento 2, one of the leading eCommerce platforms, provides robust REST APIs that empower developers to create and update products programmatically. Whether you’re launching a new catalog, syncing inventory, or fine-tuning product details, the REST API is your gateway to seamless automation.

Imagine this: with just a few API calls, you can transform how you manage product data—eliminating manual entry, reducing errors, and saving precious time. In this guide, we’ll walk you through how to create and update products effortlessly using REST API in Magento 2. Ready to supercharge your product management? Let’s dive in!

Prerequisites for Using Magento 2 API

Before making API calls to update products or perform other tasks in Magento 2, ensure the following requirements are met:

  • Magento 2 Setup: A working Magento 2 installation.
  • Admin Access: Access to the Magento Admin Panel.
  • API Token: Generate an admin access token for authentication.
  • API Tool: Use tools like Postman, cURL, or custom scripts to make API requests.

How to Create Products Using REST API in Magento 2

Step 1: Plan The Product

Define The Simple Product Characteristics

Note:

  • The payloads for creating a simple product and a configurable product are similar, with the following exceptions:
    • The simple product sku attaches the configurable option to the configurable product sku.
    • The name shows the size.
    • The type_id is set to simple.
    • The visibility is set to 1, meaning that the simple product should not be displayed on the store.
    • The price and size attributes are specified.
  • Although it is not required, the simple product payload also contains stock_item information. By default, out-of-stock items are hidden, so adding stock will make the product visible on the website.

Assuming that we need to create a small Dime t-shirt as a single product in Magento 2. The following table displays the attributes of the men t-shirt we are creating:

Characteristic Description
Attribute Set Top
Product Name Dime Tee Small
SKU MS-Dime-S
Price 30
Tax Class Taxable Goods
Weight 0.6
Categories Men, Tops, Tees
Visibility Not display on the store
Material LumaTech
Pattern Graphic Print
Color Gray
Size Small
Description The Dime Tee is soft, comfortable and durable. You will love the way you look in this tailored tee shirt.

The online store typically gives the product name, SKU, price, weight, and description. The system defines other attributes.

Find The System-Defined Values

To find the values needed to create the product, we have to make several calls.

Step 2: Create The First Simple Product

Please use the below code sample to create the first simple product.

Endpoint

POST <host>/rest/default/V1/products

Payload

{
  "product": {
    "sku": "MS-Dime-S",
    "name": "Dime Tee Small",
    "attribute_set_id": 9,
    "price": 25,
    "status": 1,
    "visibility": 1,
    "type_id": "simple",
    "weight": "0.6",
    "extension_attributes": {
    	"category_links": [
    		{
    			"position": 0,
    			"category_id": "11"
    		},
    		{
    			"position": 1,
    			"category_id": "12"
    		},
    		{
    			"position": 2,
    			"category_id": "16"
    		}
    	],
    	"stock_item": {
    		"qty": "10",
    		"is_in_stock": true
    	}
    },
    "custom_attributes": [
    	{
    		"attribute_code": "description",
    		"value": "The Dime Tee is soft, comfortable and durable. You will love the way you look in this tailored tee shirt."
    	},
    	{
    		"attribute_code": "tax_class_id",
    		"value": "2"
    	},
    	{
    		"attribute_code": "material",
    		"value": "148"
    	},
    	{
    		"attribute_code": "pattern",
    		"value": "196"
    	},
    	{
    		"attribute_code": "color",
    		"value": "52"
    	},
    	{
    		"attribute_code": "size",
    		"value": "168"
    	}
    ]
  }
}

Response

{
    "id": 2079,
    "sku": "MS-Dime-S",
    "name": "Dime Tee Small",
    "attribute_set_id": 9,
    "price": 25,
    "status": 1,
    "visibility": 1,
    "type_id": "simple",
    "created_at": "2017-11-29 20:40:07",
    "updated_at": "2017-11-29 20:40:07",
    "weight": 0.6,
    "extension_attributes": {
        "website_ids": [
            1
        ],
        "category_links": [
            {
                "position": 0,
                "category_id": "11"
            },
            {
                "position": 1,
                "category_id": "12"
            },
            {
                "position": 2,
                "category_id": "16"
            }
        ],
        "stock_item": {
            "item_id": 2079,
            "product_id": 2079,
            "stock_id": 1,
            "qty": 10,
            "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": [],
    "tier_prices": [],
    "custom_attributes": [
        {
            "attribute_code": "description",
            "value": "The Dime Tee is soft, comfortable and durable. You will love the way you look in this tailored tee shirt."
        },
        {
            "attribute_code": "color",
            "value": "52"
        },
        {
            "attribute_code": "category_ids",
            "value": [
                "11",
                "12",
                "16"
            ]
        },
        {
            "attribute_code": "options_container",
            "value": "container2"
        },
        {
            "attribute_code": "required_options",
            "value": "0"
        },
        {
            "attribute_code": "has_options",
            "value": "0"
        },
        {
            "attribute_code": "url_key",
            "value": "champ-tee-small"
        },
        {
            "attribute_code": "tax_class_id",
            "value": "2"
        },
        {
            "attribute_code": "material",
            "value": "148"
        },
        {
            "attribute_code": "size",
            "value": "168"
        },
        {
            "attribute_code": "pattern",
            "value": "196"
        }
    ]
}

Step 3: Create The Other Simple Products

If you want to create other simple products (for example Dime Tee in medium or large size), repeat the call with the following changes to the payload:

Attribute Medium Value Large Value
sku MS-Dime-M MS-Dime-L
name Dime Tee Medium Dime Tee Large
size 169 170

Step 4: Verify The Results

  • Access your admin panel and navigate to Catalog > Products. Now you will see the products on the grid.
  • Search for Dime on your storefront page. No results are shown.

How to Update Product Using API in Magento 2

Updating a product in Magento 2 can be done efficiently via the API. Below are the steps and details for achieving this:

API Endpoint: /rest/V1/products/{SKU}

Request Method: PUT

Request Body:

{
  "product": {
    "price": 20000,
    "custom_attributes": [
      {
        "attribute_code": "color",
        "value": "47"
      }
    ]
  }
}

Steps to Update a Product

  1. Open Swagger or API documentation
  • Navigate to the Swagger interface to explore Magento APIs:
/swagger/# - Alternatively, refer to Magento's official API documentation. 2. Identify the product SKU - Determine the SKU of the product you want to update. Replace {SKU} in the API URL with the product's actual SKU. 3. Configure the request - Use an API client like Postman or cURL. - Select the PUT method. - Set the API endpoint URL (/rest/V1/products/{SKU}). 4. Set request headers - Include the following headers for authentication and content type: - Authorization: Bearer (Replace with your generated token from Magento admin). - Content-Type: application/json 5. Input the JSON payload - Add the request body with the required updates, as shown above. Example: Update the product price to 20000 and set the color attribute (attribute_code: "color") to 47. 6. Execute the request - Send the request. If successful, you will receive a response confirming the product has been updated. ## Common Issues and Troubleshooting When working with the Magento 2 API, you may encounter some common issues. Here's how to identify and resolve them: ### 1. Authentication errors The request fails due to missing or invalid authentication. **Solution:** - Ensure the admin token is included in the Authorization header: ``Authorization: Bearer `` - Double-check that the admin username and password used to generate the token are correct. - If the token expires or becomes invalid, regenerate it. ### 2. Validation errors The API request fails due to missing or invalid data in the payload. **Solution:** - Require fields: - Verify all required fields for the product are included in the request, such as SKU, name, price, and attribute_set_id. - Verify Attribute Set ID: - Use the following endpoint to fetch available attribute sets and their IDs: ``GET /rest/V1/eav/attribute-sets/list`` - Confirm the correct attribute_set_id is used in the payload. - Example validation error response: ``` { "message": "The attribute_set_id field is required." } ``` ### 3. Stock update issues Stock-related updates fail or are not applied as expected. **Solution:** - Ensure proper formatting: - For stock updates, ensure extension_attributes.stock_item is correctly formatted in the payload. - Use the Stock Items Endpoint for Advanced Management: - For more complex stock updates, use the dedicated stock items API endpoint: ``POST /rest/V1/stockItems`` - Example payload for stock updates: ``` { "product_id": 123, "stock_item": { "qty": 50, "is_in_stock": true } } ``` ## Useful Tips for Using Magento 2 API to Update Products To ensure a smooth and error-free experience while updating products using the Magento 2 API, keep the following tips in mind: 1. Test in a development environment - Always test API calls in a staging or development environment first to ensure there are no unexpected issues. - This helps you identify and resolve errors without affecting the live website. 2. Backup before updates - [Create backups of your product data and database](https://www.mageplaza.com/kb/how-to-create-backups-magento-2.html) before making updates. - This protects against accidental data loss or corruption during API operations. - Use Magento's built-in backup features or third-party tools. 3. Use batch updates for efficiency - For bulk product updates, consider using the PUT /rest/V1/products endpoint with an array of products in a single request. - Batch updates save time and reduce the number of API calls. 4. Log API responses - Always log the responses from your API requests, including both successes and errors. - This is crucial for debugging and tracking changes made via the API. - Use tools or frameworks that integrate logging, such as Monolog for PHP. ## Conclusion Using the Magento 2 REST API for product management streamlines inventory updates and integrations. By following the steps outlined in this guide, you can effectively create and update products, ensuring your eCommerce store remains up-to-date and efficient.
x
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services