Magento 2 REST API: Part 4, Category Creation…

One of the things I found to be a challenge was creating over 200 categories. The company I work for has a lot of different brands, categories, and a very large sku catalog. I didn’t want to farm this out and take money away from development, so I decided to do it myself. After assembling my CSV, I was ready to go to work with the Category REST API.

The JSON is actually pretty simple:

	"category": {
		"name": "Emission System",
		"level": 1,
		"path": "1",
		"isActive": true
	"saveOptions": true

This creates a category underneath the Default category named ‘Emission System’. Let me explain further.

“name” is what you will name the category, what will be displayed to your customers.

“level” is your subcategory level. If you didn’t want to put your category under the default category, you can change this to 0, and don’t include the path.

“path” is the Magento path. You can look at the database table ‘catalog_category_entity’ to see what you should set this as. For me, being that it was under the Default category, I set the path to 1, which is it’s entity_id. As I said in the level description, you can leave this out if you’re making a top-level category.

“isActive” is required, and should be set to true or false.

There are also many more attributes you can set. See the Magento docs for those: Magento REST API Reference. (See catalogCategoryRepositoryV1 and look at POST /V1/categories)

Here’s some php code to send it:

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

$ch = curl_init( "" );

$curlOptions = array(
    CURLOPT_POSTFIELDS => $newCategoryJson,
    CURLOPT_HTTPHEADER => array( "Content-type: application/json", "Authorization: bearer kalfjkkwjelfkjwelf" )

curl_setopt_array( $ch, $curlOptions );

$response = curl_exec( $ch );

One final tidbit of information that could help you. For the path and level, explore that database table. If you have too, create a category and then subcategory and see how it saves it in the database. You can get your level and path information from there for your category API send. This helped me build a tree of categories 4 levels deep. After a couple, I didn’t even need to look it, it came naturally. It can for you too.

By now you should be seeing that the Magento REST API has some recurring themes and is put together pretty nice. This will help you as different parts of the API come across your path and the docs are a little sketchy. Creating categories will be quick and easy.


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.