Magento 2 API – Wishlist [Custom API]
Magento Integration Made Easy!
Integrate any third-party tool or service with your store using our Magento API Integration Services.
Are you looking for Magento 2 API for Wishlist functionality? In the post, I’ll share the Magento 2 Wishlist REST API module to add, view, move, and delete items from the Wishlist.
Product wishlist is an important feature of any online shopping store/app. Magento 2 (Adobe Commerce) offers the product Wishlist functionality by default. It allows the customers to save products they wish to buy.
The Magento 2 API makes it easy for developers to access its features from other apps or platforms. But, there is no native API endpoint for the Wishlist functionality in Magento 2. Therefore, you may need to develop a custom Magento 2 API to access the Wishlist features.
Well, I’ve done the hard work for you! Recently, I developed a custom API module in Magento 2 to access the Wishlist features for a mobile app. In this post, I am going to share the complete module with you!
This post covers
Let’s get started with the Magento 2 Wishlist REST API module.
Create a Magento 2 Wishlist REST API Module
In order to create a custom web API in Magento 2, we need to create a custom module. The module defines the route for the Magento 2 API endpoint, along with its functions. Below is a step-wise method to create the Magento 2 REST API module for Wishlist.
Note: Replace ‘Meetanshi’ & CustomRestApi in the below provided codes with your vendor name and module name. The directory of each of the files will also change accordingly.
Step 1: Create and Register a Custom API Module
First, you need to register the custom API module for Wishlist in Magento 2. For that, create module.xml and registration.php files at the following directory:
- app/code/Meetanshi/CustomRestApi/etc/module.xml
1234<?xml version=”1.0″?><config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:Module/etc/module.xsd”><module name=”Meetanshi_CustomRestApi” setup_version=”0.0.1″/></config>
- app/code/Meetanshi/CustomRestApi/registration.php
123456<?php\Magento\Framework\Component\ComponentRegistrar::register(\Magento\Framework\Component\ComponentRegistrar::MODULE,‘Meetanshi_CustomRestApi’,__DIR__);
Step 2: Define Custom Endpoint
Now, define the endpoint for the custom REST API in Magento 2 for the Wishlist. To do that, you need to create a webapi.xml file as presented below:
- \app\code\Meetanshi\CustomRestApi\etc\webapi.xml
123456789101112131415161718192021222324252627282930313233<route url=”/V1/wishlist” method=”POST”><service class=”Meetanshi\CustomRestApi\Api\WishlistManagementInterface” method=”add”/><resources><resource ref=”self”/></resources><data><parameter name=”customerId” force=”true”>%customer_id%</parameter></data></route><route url=”/V1/wishlist” method=”GET”><service class=”Meetanshi\CustomRestApi\Api\WishlistManagementInterface” method=”get”/><resources><resource ref=”self”/></resources><data><parameter name=”customerId” force=”true”>%customer_id%</parameter></data></route><route url=”/V1/wishlist/:itemId” method=”DELETE”><service class=”Meetanshi\CustomRestApi\Api\WishlistManagementInterface” method=”delete”/><resources><resource ref=”self”/></resources><data><parameter name=”customerId” force=”true”>%customer_id%</parameter></data></route><route url=”/V1/wishlist/move” method=”POST”><service class=”Meetanshi\CustomRestApi\Api\WishlistManagementInterface” method=”move”/><resources><resource ref=”self”/></resources><data><parameter name=”customerId” force=”true”>%customer_id%</parameter></data></route>
Step 3: Configure Module Dependency
Create a di.xml file for the Magento 2 module as shown below:
- \app\code\Meetanshi\CustomRestApi\etc\di.xml
1234<?xml version=”1.0″?><config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:ObjectManager/etc/config.xsd”><preference for=”Meetanshi\CustomRestApi\Api\WishlistManagementInterface” type=”Meetanshi\CustomRestApi\Model\WishlistManagement”/></config>
Step 4: Create an Interface for the Request
Create an interface for Magento 2 Wishlist API. You can do this by adding the following file:
- \app\code\Meetanshi\CustomRestApi\Api\WishlistManagementInterface.php
123456789101112131415161718192021222324<?phpnamespace Meetanshi\CustomRestApi\Api;interface WishlistManagementInterface{/* @param int $customerId* @return \Meetanshi\CustomRestApi\Api\Data\WishlistInterface*/public function get(int $customerId);/* @param int $customerId* @param \Meetanshi\CustomRestApi\Api\Data\RequestInterface $item* @return \Meetanshi\CustomRestApi\Api\Data\WishlistInterface*/public function add(int $customerId, $item);/* @param int $customerId* @param int $quoteId* @param int $itemId* @return \Meetanshi\CustomRestApi\Api\Data\WishlistInterface*/public function move(int $customerId, int $quoteId, int $itemId);/* @param int $customerId* @param int $itemId* @return bool*/public function delete(int $customerId, int $itemId): bool;}
Step 5: Create a Model
Lastly, create a model for the Magento 2 Wishlist API.
- \app\code\Meetanshi\CustomRestApi\Model\WishlistManagementbb.php
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253<?phpnamespace Meetanshi\CustomRestApi\Model;use Magento\Catalog\Api\ProductRepositoryInterface;use Magento\Framework\DataObject;use Magento\Framework\Event\ManagerInterface;use Magento\Framework\Exception\LocalizedException;use Magento\Framework\Exception\NoSuchEntityException;use Magento\Wishlist\Model\WishlistFactory;use Meetanshi\CustomRestApi\Api\WishlistManagementInterface;class WishlistManagement implements WishlistManagementInterface{/*** @var WishlistFactory*/private $wishlistFactory;/*** @var ProductRepositoryInterface*/private $productRepository;/*** @var ManagerInterface*/private $eventManager;/*** @var \Magento\Catalog\Helper\Product\Configuration*/private $productHelper;/*** WishlistManagement constructor.* @param WishlistFactory $wishlistFactory* @param ProductRepositoryInterface $productRepository* @param ManagerInterface $eventManager* @param \Magento\Catalog\Helper\Product\Configuration $productHelper*/public function __construct(WishlistFactory $wishlistFactory,ProductRepositoryInterface $productRepository,ManagerInterface $eventManager,\Magento\Catalog\Helper\Product\Configuration $productHelper) {$this->wishlistFactory = $wishlistFactory;$this->productRepository = $productRepository;$this->eventManager = $eventManager;$this->productHelper = $productHelper;}/*** @param int $customerId* @return \Magento\Wishlist\Model\Wishlist|\Meetanshi\CustomRestApi\Api\Data\WishlistInterface* @throws NoSuchEntityException*/public function get(int $customerId){$wishlist = $this->wishlistFactory->create()->loadByCustomerId($customerId);if (!$wishlist->getId()) {$wishlist[‘items’] = [];$wishlist[‘error’] = [‘Customer does not yet have a wishlist’];return $wishlist;}$objectManager = \Magento\Framework\App\ObjectManager::getInstance();$helper = $objectManager->get(‘Meetanshi\CustomRestApi\Helper\Data’);$helperPool = $objectManager->get(‘Magento\Catalog\Helper\Product\ConfigurationPool’);$storeUrl = $helper->getStoreUrl();$mediaUrl = $storeUrl . ‘/pub/media/catalog/product/’;if ($helper->isRemovePub()) {$mediaUrl = $storeUrl . ‘/media/catalog/product/’;}$product_img = [];$productItems = [];foreach ($wishlist->getItemCollection()->getItems() as $item) {$productId = $item->getProductId();try{$product = $this->productRepository->getById($productId);switch ($product->getTypeId()) {case “bundle” : $helperInstance = \Magento\Bundle\Helper\Catalog\Product\Configuration::class; break;case “downloadable” : $helperInstance = \Magento\Downloadable\Helper\Catalog\Product\Configuration::class; break;default : $helperInstance = \Magento\Catalog\Helper\Product\Configuration::class;}$productItems[] =[“wishlist_item_id” => $item->getId(),“product_id” => $productId,“name” => $product->getData(‘name’),“price” => number_format($item->getProduct()->getFinalPrice() ?? 0, 2, ‘.’, ”),“sku” => $product->getSku(),“qty” => $item->getQty(),“special_price” => number_format($item->getProduct()->getSpecialPrice() ?? 0, 2, ‘.’, ”),“image” => $mediaUrl.$product->getData(‘image’),“thumbnail” => $mediaUrl.$product->getData(‘thumbnail’),“small_image” => $mediaUrl.$product->getData(‘small_image’),“product_type” => $product->getTypeId(),“product_options” => $this->getConfiguredOptions($item, $helperPool, $helperInstance)];}catch (\Exception $e) {}}$wishlist[‘items’] = array_merge($productItems, $product_img);return $wishlist;}/*** @param $item* @param $helperPool* @param $mainHelper* @return mixed*/public function getConfiguredOptions($item, $helperPool, $mainHelper){$helper = $helperPool->get($mainHelper);$options = $helper->getOptions($item);foreach ($options as $index => $option) {if (is_array($option) && array_key_exists(‘value’, $option)) {if (!(array_key_exists(‘has_html’, $option) && $option[‘has_html’] === true)) {if (is_array($option[‘value’])) {foreach ($option[‘value’] as $key => $value) {$option[‘value’][$key] = $value;}}}$options[$index][‘value’] = $option[‘value’];}}return $options;}/*** @param int $customerId* @param \Meetanshi\CustomRestApi\Api\Data\RequestInterface $item* @return \Magento\Wishlist\Model\Wishlist|\Meetanshi\CustomRestApi\Api\Data\WishlistInterface* @throws LocalizedException* @throws NoSuchEntityException*/public function add(int $customerId, $item){$wishlist = $this->wishlistFactory->create()->loadByCustomerId($customerId, true);$product = $this->productRepository->get($item->getProduct());if (!$product->isVisibleInCatalog()) {throw new LocalizedException(__(“Sorry, this item can’t be added to wishlists”), null, 1);}$buyRequest = new DataObject();$customAttributes = $item->getCustomAttributes();if ($customAttributes) {$superAttributes = [];$bundleOptionQtys = [];$bundleOptions = [];foreach ($customAttributes as $customAttribute) {if (strpos($customAttribute->getAttributeCode(), ‘super_attribute_’) === 0) {$superAttributeId = str_replace(‘super_attribute_’, ”, $customAttribute->getAttributeCode());$superAttributes[$superAttributeId] = $customAttribute->getValue();continue;}if (strpos($customAttribute->getAttributeCode(), ‘bundle_option_qty_’) === 0) {$bundleOptionQty = str_replace(‘bundle_option_qty_’, ”, $customAttribute->getAttributeCode());$bundleOptionQtys[$bundleOptionQty] = $customAttribute->getValue();continue;}if (strpos($customAttribute->getAttributeCode(), ‘bundle_option_’) === 0) {$bundleOption = str_replace(‘bundle_option_’, ”, $customAttribute->getAttributeCode());$bundleOption = explode(‘_’, $bundleOption);if (count($bundleOption) === 1) {$bundleOptions[$bundleOption[0]] = $customAttribute->getValue();} elseif (count($bundleOption) === 2) {$bundleOptions[$bundleOption[0]][$bundleOption[1]] = $customAttribute->getValue();}continue;}}if ($superAttributes) {$buyRequest->setData(‘super_attributes’, $superAttributes);}if ($bundleOptionQtys) {$buyRequest->setData(‘bundle_option_qty’, $bundleOptionQtys);}if ($bundleOptions) {$buyRequest->setData(‘bundle_option’, $bundleOptions);}}$result = $wishlist->addNewItem($product, $buyRequest);if (is_string($result)) {throw new LocalizedException(__($result), null, 2);}if ($wishlist->isObjectNew()) {$wishlist->save();}$this->eventManager->dispatch(‘wishlist_add_product’,[‘wishlist’ => $wishlist, ‘product’ => $product, ‘item’ => $result] );$wishlist[‘items’] = $wishlist->getItemCollection()->getItems();return $wishlist;}/*** @param int $customerId* @param int $quoteId* @param int $itemId* @return \Meetanshi\CustomRestApi\Api\Data\WishlistInterface*/public function move(int $customerId, int $quoteId, int $itemId){$wishlist = $this->wishlistFactory->create()->loadByCustomerId($customerId, true);$buyRequest = new DataObject();$om = \Magento\Framework\App\ObjectManager::getInstance();$quote = $om->get(‘Magento\Quote\Model\Quote’);$quoteItems = $quote->load($quoteId)->getAllVisibleItems();$status = false;try {foreach ($quoteItems as $quoteItem) {$_productId = $quoteItem->getProductId();$product = $this->productRepository->getById($_productId);if (!$product->isVisibleInCatalog()) {throw new LocalizedException(__(“Sorry, this item can’t be added to wishlists”), null, 1);}if ($quoteItem->getId() == $itemId) {$buyRequest = $quoteItem->getBuyRequest();$status = true;break;}}$options = $buyRequest->getOptions();if ($buyRequest->getOptions()) {foreach ($buyRequest->getOptions() as $key => $option) {if (is_array($option)) {if (isset($option[‘date_internal’])) {unset($options[$key]);$options[$key] = $option[‘date_internal’];}}}$buyRequest->setData(‘options’, $options);}if ($status) {$result = $wishlist->addNewItem($product, $buyRequest);if (is_string($result)) {throw new LocalizedException(__($result), null, 2);}if ($wishlist->isObjectNew()) {$wishlist->save();}$this->eventManager->dispatch(‘wishlist_add_product’,[‘wishlist’ => $wishlist, ‘product’ => $product, ‘item’ => $result] );$wishlist[‘items’] = $wishlist->getItemCollection()->getItems();}}catch (\Exception $e) {throw new LocalizedException(__($e->getMessage()), null, 1);}return $wishlist;}/*** @param int $customerId* @param int $itemId* @return bool* @throws \Exception*/public function delete(int $customerId, int $itemId): bool{$wishlist = $this->wishlistFactory->create()->loadByCustomerId($customerId);$item = $wishlist->getItem($itemId);if (!$item) {throw new NoSuchEntityException(__(‘No item with ID %1’, $itemId), null, 1);}$item->delete();return true;}}
Magento 2 Wishlist Rest API – Complete Tutorial
The above Magento 2 Wishlist Rest APIs module allows you to perform the following actions through API:
- Get Items
- Add Items
- Delete Items
- Move Items to Cart
The Magento 2 Wishlist API is a customer API and requires the customer token for authorization. Therefore, you need to pass the customer token in the header of each of the requests for authorization.
Magento 2 Wishlist API – Get Items
Here’s how you can use this API to get wishlist items in Magento 2.
Method: GET
Endpoint URL: <store_url>/rest/V1/wishlist
Authorization: Bearer Token <customer_token>
Magento 2 Wishlist API – Add Items
Use this API reference to Magento 2 add to Wishlist programmatically.
Method: POST
Endpoint URL: <store_url>/rest/V1/wishlist
Authorization: Bearer Token <customer_token>
Body:
1 2 3 4 5 6 |
{ "item": { "product":"Gift Card", "qty":1 } } |
Magento 2 Wishlist API – Delete Items
Method: DELETE
Endpoint: <store_url>/rest/V1/wishlist/<wishlist_id>
Authorization: Bearer Token <customer_token>
Magento 2 Wishlist API – Move to Cart
Method: POST
Endpoint: <store_url>/rest/v1/wishlist/move/
Authorization: Bearer Token <customer_token>
Body:
1 2 3 4 5 |
{ "quoteId":3332, "itemId":7771 } } |
That’s everything about the Magento 2 Wishlist API. Follow the steps provided above to create the custom Magento 2 Wishlist REST API and access the Wishlist features through API.
In case you still have any doubts, feel free to ask in the comments section. I’d be happy to help you out. 😀
Thank You! 🍀
◄ Magento 2 API – Create Coupon CodeMagento 2 API – Create Credit Memo ►
Connect your Magento store with any third-party tool or service & improve your business efficiency.
Siddharth Nandava
Siddharth Nandava is an enthusiastic Jr Magento developer at Meetanshi. Apart from the work, you can find him learning new things and spending quality time with his family.
Prev
Shopify Image Optimization: Tips + Image Optimizer Apps
Google I/O 2023 Highlights: 30 Key Announcements You Need to Know
Next