1

I've created an extension , while visiting

magento.com/rest/V1/wishlist/1/2

it throws error.

here are my files -

di.xml

<?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="YourCompany\WishlistWebService\Api\WishlistManagementInterface" type="YourCompany\WishlistWebService\Model\WishlistManagement" />
</config>

webapi.xml

<?xml version="1.0" ?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route url="/V1/wishlist/:customerId" method="GET">
        <service class="YourCompany\WishlistWebService\Api\WishlistManagementInterface" method="getWishlistForCustomer"/>
        <resources>
            <resource ref="anonymous" />
        </resources>
    </route>
    <route url="/V1/wishlist/:customerId/:productId" method="POST">
        <service class="YourCompany\WishlistWebService\Api\WishlistManagementInterface" method="addWishlistForCustomer"/>
        <resources>
            <resource ref="anonymous" />
        </resources>
    </route>    
    <route url="/V1/wishlist/:customerId/:productId" method="DELETE">
        <service class="YourCompany\WishlistWebService\Api\WishlistManagementInterface" method="addWishlistForCustomer"/>
        <resources>
            <resource ref="anonymous" />
        </resources>
    </route>    
</routes>

Api/WishlistManagementInterface.php

<?php
/**
 * A Magento 2 module named YourCompany/WishlistWebService
 *  
 */
namespace YourCompany\WishlistWebService\Api;

/**
 * Interface WishlistManagementInterface
 * @api
 */
interface WishlistManagementInterface
{

    /**
     * Return Wishlist items.
     *
     * @param int $customerId
     * @return string
     */
    public function getWishlistForCustomer($customerId);

    /**
     * Return Added wishlist item.
     *
     * @param int $customerId
     * @param int $productId
     * @return bool
     *
     */
    public function addWishlistForCustomer($customerId,$productId);

}

YourCompany\WishlistWebService\Model\WishlistManagement.php

<?php
/**
 * A Magento 2 module named YourCompany/WishlistWebService
 *  
 */
namespace YourCompany\WishlistWebService\Model;

use YourCompany\WishlistWebService\Api\WishlistManagementInterface;
use Magento\Wishlist\Controller\WishlistProvider;
use Magento\Wishlist\Model\ResourceModel\Item\CollectionFactory;
use Magento\Wishlist\Model\WishlistFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Catalog\Helper\ImageFactory as ProductImageHelper;
use Magento\Store\Model\App\Emulation as AppEmulation;
/**
 * Defines the implementaiton class of the WishlistManagementInterface
 */
class WishlistManagement implements WishlistManagementInterface
{

    /**
     * @var CollectionFactory
     */
    protected $_wishlistCollectionFactory;

    /**
     * Wishlist item collection
     *
     * @var \Magento\Wishlist\Model\ResourceModel\Item\Collection
     */
    protected $_itemCollection;

    /**
     * @var WishlistRepository
     */
    protected $_wishlistRepository;

    /**
     * @var ProductRepository
     */
    protected $_productRepository;

    /**
     * @var WishlistFactory
     */
    protected $_wishlistFactory;

    /**
     * @var Item
     */
    protected $_itemFactory;

    /**
     * @var \Magento\Customer\Model\Customer
     */
    protected $_customer;

    /**
     *@var \Magento\Catalog\Helper\ImageFactory
     */
    protected $productImageHelper;

    /**
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storemanagerinterface;

    /**
     *@var \Magento\Store\Model\App\Emulation
     */
    protected $appEmulation;

    /**
     *@var \Magento\Catalog\Model\Product
     */
    protected $_productload;

    /**
     *@var \Magento\Directory\Model\CountryFactory
     */
    protected $countryfactory;

    /**
     * @param CollectionFactory $wishlistCollectionFactory
     * @param \Magento\Catalog\Model\ProductFactory $productFactory
     * @param \Magento\Framework\Math\Random $mathRandom
     * @param \Magento\Customer\Model\Customer $customer
     * @param \Magento\Framework\Stdlib\DateTime $dateTime
     * @param ProductRepositoryInterface $productRepository
     */
    public function __construct(
        CollectionFactory $wishlistCollectionFactory,
        WishlistFactory $wishlistFactory,
        \Magento\Customer\Model\Customer $customer,
        AppEmulation $appEmulation,
        \Magento\Directory\Model\CountryFactory $countryfactory,
        \Magento\Store\Model\StoreManagerInterface $storemanagerinterface,
        ProductImageHelper $productImageHelper,
        \Magento\Catalog\Model\Product $productload,
        \Magento\Wishlist\Model\WishlistFactory $wishlistRepository,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Wishlist\Model\ItemFactory $itemFactory
    ) {
        $this->_wishlistCollectionFactory = $wishlistCollectionFactory;
        $this->_wishlistRepository = $wishlistRepository;
        $this->_productRepository = $productRepository;
        $this->_wishlistFactory = $wishlistFactory;
        $this->countryfactory = $countryfactory;
        $this->storemanagerinterface = $storemanagerinterface;
        $this->_itemFactory = $itemFactory;
        $this->_customer = $customer;
        $this->_productload = $productload;
        $this->appEmulation = $appEmulation;
        $this->productImageHelper = $productImageHelper;
        $this->_customer = $customer;
    }

    /**
     * Get wishlist collection
     * @deprecated
     * @param $customerId
     * @return string
     */
    public function getWishlistForCustomer($customerId)
    {

        if (empty($customerId) || !isset($customerId) || $customerId == "") {
            throw new InputException(__('Id required'));
        } else {
            $collection =
                $this->_wishlistCollectionFactory->create()
                    ->addCustomerIdFilter($customerId);
            $baseurl = $this->storemanagerinterface->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'catalog/product';
            $wishlistData = [];
            foreach ($collection as $item) {
                $productInfo = $item->getProduct()->toArray();
                if ($productInfo['small_image'] == 'no_selection') {
                  $currentproduct = $this->_productload->load($productInfo['entity_id']);
                  $imageURL = $this->getImageUrl($currentproduct, 'product_base_image');
                  $productInfo['small_image'] = $imageURL;
                  $productInfo['thumbnail'] = $imageURL;
                }else{
                  $imageURL = $baseurl.$productInfo['small_image'];
                  $productInfo['small_image'] = $imageURL;
                  $productInfo['thumbnail'] = $imageURL;
                }
                $data = [
                    "wishlist_item_id" => $item->getWishlistItemId(),
                    "wishlist_id"      => $item->getWishlistId(),
                    "product_id"       => $item->getProductId(),
                    "store_id"         => $item->getStoreId(),
                    "added_at"         => $item->getAddedAt(),
                    "description"      => $item->getDescription(),
                    "qty"              => round($item->getQty()),
                    "product"          => $productInfo
                ];
                $wishlistData[] = $data;
            }
            return $wishlistData;
        }
    }

    /**
     * Add wishlist item for the customer
     * @param int $customerId
     * @param int $productId
     * @return bool
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function addWishlistForCustomer($customerId, $productId)
    {
        if ($productId == null) {
            throw new LocalizedException(__
            ('Invalid product, Please select a valid product'));
        }
        try {
            $product = $this->_productRepository->getById($productId);
        } catch (NoSuchEntityException $e) {
            $product = null;
        }
        try {
            $wishlist = $this->_wishlistRepository->create()->loadByCustomerId
            ($customerId, true);
            $wishlist->addNewItem($product);
            $returnData = $wishlist->save();
        } catch (NoSuchEntityException $e) {

        }
        return true;
    }    

    /**
     * Helper function that provides full cache image url
     * @param \Magento\Catalog\Model\Product
     * @return string
     */
    public function getImageUrl($product, string $imageType = ''){
        $storeId = $this->storemanagerinterface->getStore()->getId();
        $this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);
        $imageUrl = $this->productImageHelper->create()->init($product, $imageType)->getUrl();
        $this->appEmulation->stopEnvironmentEmulation();

        return $imageUrl;
    }
}

Please help me solve this. Thanks

  • you should try it with magento.com/rest/V1/all/wishlist/1/2 – Yasir Latif Jun 17 at 13:00
  • not working here – devmage Jun 17 at 13:35
  • give me 10 mins will post the answer – Yasir Latif Jun 17 at 13:35
  • ok sure , that will be great – devmage Jun 17 at 13:37
  • give me a min it works for me with store code in request – Yasir Latif Jun 17 at 14:08
0

first of all your need to create a module in the app directory of your root directory of Magento installation

  1. create a file etc/module.xml
  2. Create registration file for the module registation.php

etc/module.xml

<?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="YourCompany_WishlistWebService" setup_version="1.0.0">
    </module>
</config>

YourCompany/WishlistWebService/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'YourCompany_WishlistWebService',
    __DIR__
);

bin/magento setup:upgrade and di compile

rest your api module and interface is fine

if you need postman collection for above endpoints let me know i run all on my local works fine

| improve this answer | |
  • Sir this code is already there. i just have not posted it. – devmage Jun 17 at 14:04
  • not working dude – devmage Jun 18 at 4:49
  • Please check with ursite.com/swagger add bearer token and see your module there in postman check it with post request – Yasir Latif Jun 18 at 5:58
  • [2020-06-18 07:54:16] main.CRITICAL: Report ID: webapi-5eeb1da83690a; Message: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'magento2.catalog_category_product_index_store0' doesn't exist, query was: SELECT main_table.* FROM wishlist_item AS main_table – devmage Jun 18 at 7:56
  • This error appears – devmage Jun 18 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.