Magento – Magento2 add to cart REST API

addtocartapimagento2

I want step by step Magento 2 REST API add to cart
I am trying this
post/rest/V1/guest-carts it generate cart Id , then
post/rest/V1/guest-carts/:cart Id/items and I am getting error message like
this

{
        "message": "Consumer is not authorized to access %resources",
        "parameters": {
            "resources": "Magento_Cart::manage"
        }
    }

Best Answer

Try following way:

Step 1: Create auth token


$userData = array("username" => "admin", "password" => "admin123");
$ch = curl_init("http://magento.local.com/index.php/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));

$token = curl_exec($ch);

Step 2: Load/Create Customer Quote


$customerData = [
    'customer_id' => 2
];
$ch = curl_init("http://magento.local.com/index.php/rest/V1/carts/mine");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($customerData));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

$result = curl_exec($ch);

$quote_id = json_decode($result, 1);
echo '<pre>';print_r($quote_id);

Step 3: Add product to cart


$productData = [
    'cart_item' => [
        'quote_id' => $quote_id,
        'sku' => '24-MB01',
        'qty' => 1
    ]
];
$ch = curl_init("http://magento.local.com/index.php/rest//V1/carts/mine/items");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($productData));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

$result = curl_exec($ch);

$result = json_decode($result, 1);
echo '<pre>';print_r($result);

Step 4: Check current quote/cart status


$ch = curl_init("http://magento.local.com/index.php/rest//V1/carts/".$quote_id);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

$result = curl_exec($ch);

$result = json_decode($result, 1);
echo '<pre>';print_r($result);