1

I'm developing an Angular frontend that uses Magento 2 REST API. I want to get the list of my bestseller products but can't find a way to get this with the APIs.

How do I retrive this list?

Thank you!

0

By Default there doesn't look to be a bestsellers endpoint, you would need to create your own using the Sales\Model\ResourceModel\Report\Bestsellers

You can see more information on how to create a custom API here

1

Get the Bestseller Product with REST API follow below Filepath and create custom API to get Bestseller Products collection.

Filepath: magento/app/code/Vendor/Bestseller/registration.php

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

Filepath: magento/app/code/Vendor/Bestseller/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="Vendor_Bestseller" setup_version="1.0.0"/>
</config>

Filepath: magento/app/code/Vendor/Bestseller/etc/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 method="GET" url="/V1/bestseller">
        <service class="Vendor\Bestseller\Api\ProductSlidersManagementInterface" method="getBestseller"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Filepath: magento/app/code/Vendor/Bestseller/etc/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="Vendor\Bestseller\Api\ProductSlidersManagementInterface" type="Vendor\Bestseller\Model\ProductSlidersManagement"/>
</config>

Filepath: magento/app/code/Vendor/Bestseller/Api/ProductSlidersManagementInterface.php

<?php

namespace Vendor\Bestseller\Api;

interface ProductSlidersManagementInterface
{
     /**
     * Get Bestseller Product Slider api
     * @param int $currentPage
     * @param int $pageSize
     * @return \Vendor\Bestseller\Api\Data\ProductSlidersInterface
     */
    public function getBestseller($currentPage = 1, $pageSize = 10);
}

Filepath: magento/app/code/Vendor/Bestseller/Api/Data/ProductSlidersInterface.php

<?php

namespace Vendor\Bestseller\Api\Data;

/**
 * ProductSlidersInterface interface.
 * @api
 */
interface ProductSlidersInterface
{
    /**
    * @return \Vendor\Bestseller\Api\Data\ProductSlidersInterface[]
     */
    public function getBestsellerProduct();

    /**
     * @param string $bestsellerProduct
     * @return $this
     */
    public function setBestsellerProduct($bestsellerProduct);

    /**
    * @return \Vendor\Bestseller\Api\Data\FeaturedSlidersInterface[]
     */
    public function getProductCount();

    /**
     * @param string $productCount
     * @return $this
     */
    public function setProductCount($productCount);  
}

Filepath: magento/app/code/Vendor/Bestseller/Model/ProductSlidersManagement.php

<?php
namespace Vendor\Bestseller\Model;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Store\Model\StoreManagerInterface;

class ProductSlidersManagement implements \Vendor\Bestseller\Api\ProductSlidersManagementInterface
{
    const PAGINATION = 10;
    const CURRENTPAGE = 1;

    protected $dataObjectFactory;    
    protected $_collectionFactory;
    protected $storeManager;
    protected $productRepository;
    protected $storeManagerInterface;

    public function __construct(
        \Magento\Framework\DataObjectFactory $dataObjectFactory,
        \Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $collectionFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        ProductRepositoryInterface $productRepository,
        StoreManagerInterface $storeManagerInterface
    ) {
        $this->dataObjectFactory = $dataObjectFactory;
        $this->_collectionFactory = $collectionFactory;
        $this->storeManager = $storeManager;
        $this->productRepository = $productRepository;
        $this->storeManagerInterface = $storeManagerInterface;
    }

    public function getBestseller($currentPage = 1, $pageSize = 10) 
    {
        $result = $this->dataObjectFactory->create();
        if($pageSize == 0) {
            $pageSize = self::PAGINATION;
        }
        if($currentPage == 0) {
            $currentPage = self::CURRENTPAGE;
        }

        $storeId = $this->storeManager->getStore()->getId();
        $mediaUrl = $this->storeManagerInterface->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
        $bestSellerProdcutCollection = $this->_collectionFactory->create()
        ->setModel('Magento\Catalog\Model\Product')
        ->setPeriod('month')
        ->setPageSize(
            $pageSize
        )->setCurPage(
            $currentPage
        ); //you can add period daily,yearly
        //->setPeriod('year');
        //->setPeriod('day');

        $productData = [];
        $i = 0;
        $productCount = count($bestSellerProdcutCollection);
        foreach ($bestSellerProdcutCollection as $value) {
            $productId = $value->getProductId();
            $product = $this->productRepository->getById($productId);

            $productData[$i]['product_id'] = $product->getEntityId();
            $productData[$i]['name'] = $product->getName();
            $productData[$i]['price'] = $product->getPrice();
            $productData[$i]['sku'] = $product->getSku();  
            $productData[$i]['image'] = ($product->getImage())?$mediaUrl.'catalog/product'.$product->getImage():'';
            $i++;   
        }
        $result->setData('bestseller_product', $productData);
        $result->setData('product_count', $productCount);
        return $result;
    }
    
}

API: {baseurl}/V1/bestseller

Params: currentPage: 1
pageSize: 10

Method: GET

1
  • I am getting this error Consumer is not authorized to access %resources, how to fix it, I used exactly all your codes. Please help me – Mujahidh Jun 14 at 7:53
0

I created an extension that fetches best seller products via Rest API https://github.com/troublediehard/mma-customapi

2
  • NIce one, thank you Dmitri! – Leonardo Minati Oct 7 '19 at 6:59
  • @LeonardoMinati feel free to upvote the answer if you like it. – Dima Portenko Oct 7 '19 at 7:04

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.