Magento 2 REST API: Part 3, Product Updates, Pricing & QTY…

Updating your products is about the same process as creating them. You’re going to utilize the same API (/rest/V1/products).

The way we approach putting products up on our web site is to stock everything with a qty 0, and then the current price for the day its pushed over to the web site. From there our sales and marketing team will do daily updates of the current pricing and send over an update thru the REST API. Additionally, we have a cron setup that pulls inventory files and updates qty levels every few hours. This is where my talk about product updates and qty/price comes into play.

Here’s what I send for price and qty updates:

{
	"product": {
		"sku": "ABC_123456",
		"price": 324.99,
		"extensionAttributes": {
			"stockItem": {
				"qty": 120,
				"isInStock": true
			}
		}
	},
	"saveOptions": true
}

Something interesting I found was the “isInStock” attribute. The first time I sent over a qty update, I didn’t set this. In Magento, my product was at 0 qty and set to Out Of Stock. When I sent over the qty 120, it changed the isInStock to true. The same was also the case when I had it set to false. I am not sure if that is intended functionality, or a lingering bug/oversight, but as of 2.0.4, this is how it works.

Let’s put this all together with a curl exec.

$productUpdateJson = "however you want to build your json to match the above";

$ch = curl_init( "http://mymagentosite.com/index.php/rest/V1/products" );

$curlOptions = array(
    CURLOPT_CUSTOMREQUEST  => "POST",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS => $productsJson,
    CURLOPT_HTTPHEADER => array( "Content-type: application/json", "Authorization: bearer kalfjkkwjelfkjwelf" )
);

curl_setopt_array( $ch, $curlOptions );

$response = curl_exec( $ch );

Look familiar? This is the same code from Part 2. It is exactly the same operation, we’re just using minimal attributes and Magento is triggering an update since the sku exists.

You can see all the optional and required items at the official doc’s url: Magento REST API Reference. Scroll to “catalogProductRepositoryV1” and click on the POST /V1/products.

Now you not only know how to create a new product through the Magento 2 REST API, you also know how to update and manage them.

-Dan

Written by Dan
Welcome to my blog! Here you'll find my collection of bible study lessons, book reviews, and other posts I feel inspired to write. I am a Christian currently serving at First Baptist Church of Northville in Northville, MI.