How to use Magento 2 REST API?

  • author-img Nidhi Arora
  • 7 years
Magento 2 REST API?

Magento has provided a tool “swagger” that we can use to check all the API response.

We can access swagger on our Magento installation:

http:///swagger

It will list all the API resources and we can try them out. We just need to apply admin token on the top to use it.

We can use below code to create admin token:

$userData = array(“username” => “”, “password” => “”);
$ch = curl_init(“http:///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);
$token = json_decode($token);

So, using above approach you can test the API response.

Here is an example to get product detail using REST API:

$ch = curl_init(http:///rest/V1/products/”.$sku);
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);

How to create custom REST API:

There are no. Of APIs already present, but sometimes we may need functionality that is not present in default APIs list, so in that case we can create our custom API:

Alan Kent has shared in his blog how to create custom API https://alankent.me/2015/07/24/creating-a-new-rest-web-service-in-magento-2/

With the help of this blog we have created our own API, add to /remove from wishlist.

Here are the steps:

Create custom Magento2 module and add code shared below:

1. app/code/Eecom/Connector/etc/module.xml

?xml version=”1.0″?
config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd”
module name=”Eecom_Connector” setup_version=”1.0.0″
/module
/config

2. app/code/Eecom/Connector/etc/di.xml

?xml version=”1.0″?
!–
/**
* Copyright © 2017 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
–>
config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:noNamespaceSchemaLocation=”urn:magento:framework:ObjectManager/etc/config.xsd”
preference for=”Eecom\Connector\Api\WishListMethodManagementInterface”
type=”Eecom\Connector\Model\WishListMethodManagement” /
/config

3. app/code/Eecom/Connector/etc/webapi.xml

?xml version=”1.0″?
!–
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
–>
routes xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:noNamespaceSchemaLocation=”urn:magento:module:Magento_Webapi:etc/webapi.xsd”
!– Managing Wishlist —
!– Example: curl http://127.0.0.1/rest/V1/wishlist/add/1/2 —
route url=”/V1/wishlist/add/:customerId/:productId” method=”GET”
service class=”Eecom\Connector\Api\WishListMethodManagementInterface” method=”add”/
resources
resource ref=”self”/
/resources
/route
route url=”/V1/wishlist/remove/:customerId/:itemId” method=”GET”
service class=”Eecom\Connector\Api\WishListMethodManagementInterface” method=”remove”/
resources
resource ref=”self”/
/resources
/route
/routes

4. app/code/Eecom/Connector/Api/WishListMethodManagementInterface.php

?php
/**
* Copyright © 2017 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Eecom\Connector\Api;
/**
* Interface WishListMethodManagementInterface
* @api
*/
interface WishListMethodManagementInterface
{
/**
* Return Product added to wishlist true/false.
*
* @api
* @param int $customerId
* @param int $productId
* @return \Eecom\Connector\Api\WishListMethodManagementInterface true/false
*/
public function add($customerId, $productId);
/**
* Return Product removed from wishlist true/false.
*
* @api
* @param int $customerId
* @param int $itemId
* @return \Eecom\Connector\Api\WishListMethodManagementInterface true/false
*/
public function remove($customerId, $itemId);
}

5. app/code/Eecom/Connector/Model/WishListMethodManagement.php

?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Eecom\Connector\Model;
use Eecom\Connector\Api\WishListMethodManagementInterface;
class WishListMethodManagement implements WishListMethodManagementInterface
{
/**
* Object manager
*
* @var Magento\Framework\ObjectManagerInterface
*/
protected $_objectManager;
/**
* Wishlist Repository.
*
* @var \Magento\Wishlist\Model\WishlistFactory
*/
protected $_wishlistRepository;
/**
* Product Repository.
*
* @var \Magento\Catalog\Api\ProductRepositoryInterface
*/
protected $_productRepository;
/**
* Item Repository.
*
* @var \Magento\Wishlist\Model\ResourceModel\Item\Collection
*/
protected $_itemRepository;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Wishlist\Model\WishlistFactory $wishlistRepository,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Wishlist\Model\ResourceModel\Item\Collection $itemRepository
) {
$this->_objectManager = $objectManager;
$this->_wishlistRepository= $wishlistRepository;
$this->_productRepository = $productRepository;
$this->_itemRepository = $itemRepository;
}
/**
* Return Product added to wishlist true/false.
*
* @api
* @param int $customerId
* @param int $productId
* @return \Eecom\Connector\Model\WishListMethodManagement true/false
*/
public function add($customerId, $productId){
try{
if($customerId && $productId){
try {
$product = $this->_productRepository->getById($productId);
} catch (NoSuchEntityException $e) {
$product = null;
return false;
}
$wishlist = $this->_wishlistRepository->create()->loadByCustomerId($customerId, true);
$wishlist->addNewItem($product);
$wishlist->save();
return true;
}else{
return false;
}
}catch (\Exception $e) {
return false;
}

}
/**
* Return item removed from wishlist true/false
*
* @api
* @param int $customerId
* @param int $itemId
* @return \Eecom\Connector\Model\WishListMethodManagement true/false
*/
public function remove($customerId, $itemId){
try{
if($itemId){
$item = $this->_objectManager->create(‘Magento\Wishlist\Model\Item’)->load($itemId);
if (!$item->getId()) {
return false;
}
$wishlist = $this->_wishlistRepository->create()->loadByCustomerId($customerId, true);
if (!$wishlist) {
return false;
}
try{
$item->delete();
$wishlist->save();
return true;
}catch (\Exception $e) {
return false;
}
}else{
return false;
}
}catch (\Exception $e) {
return false;
}
}
}

After adding the above code, and flushing cache, new created APIs will be listed on the swagger to check the response.

Here is code to call these APis:

Add to wish List

$ch = curl_init(“http:///rest/V1/wishlist/add/”/”);
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, True);

Remove from wishlist

$ch = curl_init(“http:///rest/V1/wishlist/remove//”);
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, True);

If you still have any query regarding this “How to” or would like to add some suggestions to this solution, let us know your feedback or query at sales@envisionecommerce.com, and don’t forget to share this “How to” blog with your fellow Magento 2 users!

Download Blog

ENQUIRY

Ready to Get Started

Communication is the key for us to understand each other. Allow us to understand
your requirements or queries. Present us with an opportunity to serve you.

Fill out the form and out team will get back to you
within 24 hours

    Head Office

    815 Brazos St STE 500, Austin,
    TX 78701, USA