Magento – How to get product collection in magento 2

apimagento2product-collection

I am trying to create an API in magento 2 to get all product information. I have prepared a simple API module and it is working fine. Now I am trying to fetch product collection, but getting an error.

Here is my Code:

<?php 

namespace CompanyName\Connector\Model;

    use Magento\Catalog\Model\Product;
    use CompanyName\Connector\Api\OdooInterface;
    use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;

    class Odoo implements OdooInterface
    {
        protected $productCollectionFactory;

        public function __construct(ProductCollectionFactory $productCollectionFactory)
        {
            $this->productCollectionFactory = $productCollectionFactory;
        }

        /**
         * Returns Product collection
         *
         * @api
         *
         * @return $collection
         */
        public function getProductCollection()
        {
            $collection = $this->productCollectionFactory->create();
            $collection->addAttributeToSelect('*');
            $collection->setPageSize(3); // fetching only 3 products
            return $collection;
        }
    }

Here is the error I am getting:

Fatal Error: 'Call to undefined method Magento\Catalog\Model\ResourceModel\Product\Collection\Interceptor::getProductCollection()' in '/var/www/html/magento2/vendor/magento/framework/Reflection/DataObjectProcessor.php' on line 86

Please let me know, if any one have solution for it.

Best Answer

OPTION 1:

You can use repositories for this and return a SearchResultsInterface.

OPTION 2:

Use Magento API \Magento\Catalog\Api\ProductRepositoryInterface witha search filter.

OPTION 3:

Change your code to return an array of ProductInterface

...
    /**
     * Returns Product collection
     *
     * @api
     *
     * @return \Magento\Catalog\Api\Data\ProductInterface[]
     */
    public function getProductCollection()
    {
        $collection = $this->productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setPageSize(3); // fetching only 3 products

        $res = [];
        foreach ($collection as $product) {
           $res[] = $product;
        }

        return $res;
    }
...

WARNING: Rememeber to set @return \Magento\Catalog\Api\Data\ProductInterface[] on your interface or it will not work