phpmagentomagento-rest-api

Assign a product to a specific category in Magento with REST API


I'm using code below to POST a product to Magento which works fine however I need know how to assign the product to a specific category. Anyone knows a solution?

Thanks in advance.

$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/products";

$productData = json_encode(array(
            'type_id'           => 'simple',
            'attribute_set_id'  => 4,
            'sku'               => 'simple' . uniqid(),
            'weight'            => 1,
            'status'            => 1,
            'visibility'        => 4,
            'name'              => 'Name of the product',
            'description'       => 'Description',
            'short_description' => 'Short Description',
            'price'             => 6.99,
            'tax_class_id'      => 0
        ));
        $headers = array('Content-Type' => 'application/json');
        $oauthClient->fetch($resourceUrl, $productData, OAUTH_HTTP_METHOD_POST, $headers);

Solution

  • Solved. This goes after adding the products into magento process.

    $productId = 100; //Extracted from the previous response
    $categoryId = 4;
    $resourceUrl = "$apiUrl/products/$productId/categories";
    $productData = json_encode(array('category_id' => $categoryId));
    $headers = array('Content-Type' => 'application/json');
    $oauthClient->fetch($resourceUrl, $productData, OAUTH_HTTP_METHOD_POST, $headers);
    $response = $oauthClient->getLastResponseInfo();