0

I want to get new product using REST API.

I am using below code:-

app/code/Myvendor/Mymodule/Api/NewproductInterface.php

    <?php
    namespace Myvendor\Mymodule\Api;

    //use Myvendor\Mymodule\Api\Data\PointInterface;

    interface NewproductInterface
    {

        /**
         * GET new product list
         *
         * @api
         * @param string $id
         * @return \Magento\Catalog\Api\Data\ProductInterface
         * @throws \Magento\Framework\Exception\NoSuchEntityException
         */
        public function newproduct();
}

app/code/Myvendor/Mymodule/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">
    <!-- Get new peoduct list -->
    <route url="/V1/custom/catalog/newproduct" method="POST">
        <service class="Myvendor\Mymodule\Api\NewproductInterface" method="newproduct"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

app/code/Myvendor/Mymodule/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="Myvendor\Mymodule\Api\NewproductInterface" type="Myvendor\Mymodule\Model\Newproduct" />
</config>

app/code/Myvendor/Mymodule/Model/Newproduct.php

use Magento\Catalog\Api\ProductRepositoryInterface;
use Myvendor\Mymodule\Api\NewproductInterface;

class Newproduct implements NewproductInterface
{
     const DEFAULT_PRODUCTS_COUNT = 10;
    //protected $searchCriteriaBuilder;
    /**   
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    protected $productRepository;
    protected $_localeDate;
    protected $_catalogConfig;
    protected $_productsCount;

    public function __construct(
       ProductRepositoryInterface $productRepository,
       //SearchCriteriaBuilder $searchCriteriaBuilder,
       \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
       \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
       \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
       \Magento\Catalog\Block\Product\Context $context
    )
    {
        $this->productRepository = $productRepository;
        //$this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->_productCollectionFactory = $productCollectionFactory;
        $this->_catalogProductVisibility = $catalogProductVisibility;
        $this->_localeDate = $localeDate;
        $this->_catalogConfig = $context->getCatalogConfig();
    }


    protected function _addProductAttributesAndPrices(
        \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
    ) {
        return $collection
            ->addMinimalPrice()
            ->addFinalPrice()
            ->addTaxPercents()
            ->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
            ->addUrlRewrite();
    }

    public function setProductsCount($count)
    {
        $this->_productsCount = $count;
        return $this;
    }

    public function getProductsCount()
    {
        if (null === $this->_productsCount) {
            $this->_productsCount = self::DEFAULT_PRODUCTS_COUNT;
        }
        return $this->_productsCount;
    }
    /**
     * {@inheritdoc}
     */
    public function newproduct()
    {
        $todayStartOfDayDate = $this->_localeDate->date()->setTime(0, 0, 0)->format('Y-m-d H:i:s');
        $todayEndOfDayDate = $this->_localeDate->date()->setTime(23, 59, 59)->format('Y-m-d H:i:s');    


        /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
        $collection = $this->_productCollectionFactory->create();
        $collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());

        $collection = $this->_addProductAttributesAndPrices(
            $collection
        )->addStoreFilter()->addAttributeToFilter(
            'news_from_date',
            [
                'or' => [
                    0 => ['date' => true, 'to' => $todayEndOfDayDate],
                    1 => ['is' => new \Zend_Db_Expr('null')],
                ]
            ],
            'left'
        )->addAttributeToFilter(
            'news_to_date',
            [
                'or' => [
                    0 => ['date' => true, 'from' => $todayStartOfDayDate],
                    1 => ['is' => new \Zend_Db_Expr('null')],
                ]
            ],
            'left'
        )->addAttributeToFilter(
            [
                ['attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')],
                ['attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null')],
            ]
        )->addAttributeToSort(
            'news_from_date',
            'desc'
        )->setPageSize(
            $this->getProductsCount()
        )->setCurPage(
            1
        );      

        //$priCount = count($collection);
        //return $priCount;

        //echo "<pre>"; print_r($collection->getData()); echo "</pre>"; die("hi");

        return $collection;
    }


    protected function _beforeToHtml()
    {
        $this->setProductCollection($this->newproduct());
        return parent::_beforeToHtml();
    }
}

When i check the collection using print_r I am able to get the collecton but when I return the collection it give me error as below in postman:

URL: http://domain.com/rest/V1/custom/catalog/newproduct

{
    "messages": {
        "error": [
            {
                "code": 500,
                "message": "Server internal error. See details in report api/1117659851420"
            }
        ]
    }
}   

Please help me how to return collection.

error log:

"Fatal Error: 'Uncaught Error: Call to undefined method Magento\\Catalog\\Model\\ResourceModel\\Product\\Collection\\Interceptor::getId() in \/vendor\/magento\/framework\/Reflection\/DataObjectProcessor.php:82\nStack trace:\n#0 \/vendor\/magento\/framework\/Webapi\/ServiceOutputProcessor.php(108): Magento\\Framework\\Reflection\\DataObjectProcessor->buildOutputDataArray(Object(Magento\\Catalog\\Model\\ResourceModel\\Product\\Collection\\Interceptor), '\\\\Magento\\\\Catalo...')\n#1 \/vendor\/magento\/framework\/Webapi\/ServiceOutputProcessor.php(60): Magento\\Framework\\Webapi\\ServiceOutputProcessor->convertValue(Object(Magento\\Catalog\\Model\\ResourceModel\\Product\\Collection\\Interceptor), '\\\\Magento\\\\Catalo...')\n#2 \/vendor\/magento\/module-webapi\/Controller\/Rest\/SynchronousRequestProcessor.php(99): Magento\\Framework\\Webapi\\ServiceOutputProcessor->process(Object(Magento\\Catalog\\Model\\ResourceM' in '\/vendor\/magento\/framework\/Reflection\/DataObjectProcessor.php' on line 82"
Purushotam Sharma
  • 1,657
  • 2
  • 26
  • 59

2 Answers2

1

Change return type for

SR/MagentoCommunity/Api/NewproductInterface.php

<?php
namespace SR\MagentoCommunity\Api;

interface NewproductInterface
{

    /**
     * GET new product list
     *
     * @api
     * @return array []
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function newproduct();
}

In

SR/MagentoCommunity/Model/Newproduct.php

Return return $collection->getData();

<?php
namespace SR\MagentoCommunity\Model;

use Magento\Catalog\Api\ProductRepositoryInterface;
use SR\MagentoCommunity\Api\NewproductInterface;

class Newproduct implements NewproductInterface
{
    const DEFAULT_PRODUCTS_COUNT = 10;
    //protected $searchCriteriaBuilder;
    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    protected $productRepository;
    protected $_localeDate;
    protected $_catalogConfig;
    protected $_productsCount;

    public function __construct(
        ProductRepositoryInterface $productRepository,
        //SearchCriteriaBuilder $searchCriteriaBuilder,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
        \Magento\Catalog\Block\Product\Context $context
    )
    {
        $this->productRepository = $productRepository;
        //$this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->_productCollectionFactory = $productCollectionFactory;
        $this->_catalogProductVisibility = $catalogProductVisibility;
        $this->_localeDate = $localeDate;
        $this->_catalogConfig = $context->getCatalogConfig();
    }


    protected function _addProductAttributesAndPrices(
        \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
    ) {
        return $collection
            ->addMinimalPrice()
            ->addFinalPrice()
            ->addTaxPercents()
            ->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
            ->addUrlRewrite();
    }

    public function setProductsCount($count)
    {
        $this->_productsCount = $count;
        return $this;
    }

    public function getProductsCount()
    {
        if (null === $this->_productsCount) {
            $this->_productsCount = self::DEFAULT_PRODUCTS_COUNT;
        }
        return $this->_productsCount;
    }
    /**
     * {@inheritdoc}
     */
    public function newproduct()
    {
        $todayStartOfDayDate = $this->_localeDate->date()->setTime(0, 0, 0)->format('Y-m-d H:i:s');
        $todayEndOfDayDate = $this->_localeDate->date()->setTime(23, 59, 59)->format('Y-m-d H:i:s');


        /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
        $collection = $this->_productCollectionFactory->create();
        $collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());

        $collection = $this->_addProductAttributesAndPrices(
            $collection
        )->addStoreFilter()->addAttributeToFilter(
            'news_from_date',
            [
                'or' => [
                    0 => ['date' => true, 'to' => $todayEndOfDayDate],
                    1 => ['is' => new \Zend_Db_Expr('null')],
                ]
            ],
            'left'
        )->addAttributeToFilter(
            'news_to_date',
            [
                'or' => [
                    0 => ['date' => true, 'from' => $todayStartOfDayDate],
                    1 => ['is' => new \Zend_Db_Expr('null')],
                ]
            ],
            'left'
        )->addAttributeToFilter(
            [
                ['attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')],
                ['attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null')],
            ]
        )->addAttributeToSort(
            'news_from_date',
            'desc'
        )->setPageSize(
            $this->getProductsCount()
        )->setCurPage(
            1
        );

        //$priCount = count($collection);
        //return $priCount;

        //echo "<pre>"; print_r($collection->getData()); echo "</pre>"; die("hi");

        return $collection->getData();
    }
}

Now output should be


Array
(
    [0] => Array
        (
            [entity_id] => 1896
            [attribute_set_id] => 17
            [type_id] => configurable
            [sku] => WP11
            [has_options] => 1
            [required_options] => 0
            [created_at] => 2019-04-25 09:31:43
            [updated_at] => 2019-04-25 09:31:43
            [cat_index_position] => 0
            [price] => 42.0000
            [tax_class_id] => 2
            [final_price] => 33.6000
            [minimal_price] => 25.2000
            [min_price] => 25.2000
            [max_price] => 33.6000
            [tier_price] => 
            [news_from_date] => 
        )

    [1] => Array
        (
            [entity_id] => 14
            [attribute_set_id] => 22
            [type_id] => simple
            [sku] => 24-WB07
            [has_options] => 0
            [required_options] => 0
            [created_at] => 2019-04-25 09:29:06
            [updated_at] => 2019-04-25 09:29:06
            [cat_index_position] => 0
            [price] => 45.0000
            [tax_class_id] => 2
            [final_price] => 45.0000
            [minimal_price] => 45.0000
            [min_price] => 45.0000
            [max_price] => 45.0000
            [tier_price] => 
            [news_from_date] => 
        )

    [2] => Array
        (
            [entity_id] => 133
            [attribute_set_id] => 16
            [type_id] => configurable
            [sku] => MH05
            [has_options] => 1
            [required_options] => 0
            [created_at] => 2019-04-25 09:29:43
            [updated_at] => 2019-04-25 09:29:43
            [cat_index_position] => 0
            [price] => 52.0000
            [tax_class_id] => 2
            [final_price] => 52.0000
            [minimal_price] => 52.0000
            [min_price] => 52.0000
            [max_price] => 52.0000
            [tier_price] => 
            [news_from_date] => 
        )

    [3] => Array
        (
            [entity_id] => 645
            [attribute_set_id] => 16
            [type_id] => configurable
            [sku] => MT01
            [has_options] => 1
            [required_options] => 0
            [created_at] => 2019-04-25 09:30:20
            [updated_at] => 2019-04-25 09:30:20
            [cat_index_position] => 0
            [price] => 29.0000
            [tax_class_id] => 2
            [final_price] => 29.0000
            [minimal_price] => 29.0000
            [min_price] => 29.0000
            [max_price] => 29.0000
            [tier_price] => 
            [news_from_date] => 
        )

    [4] => Array
        (
            [entity_id] => 996
            [attribute_set_id] => 17
            [type_id] => configurable
            [sku] => MSH09
            [has_options] => 1
            [required_options] => 0
            [created_at] => 2019-04-25 09:30:43
            [updated_at] => 2019-04-25 09:30:43
            [cat_index_position] => 0
            [price] => 24.0000
            [tax_class_id] => 2
            [final_price] => 24.0000
            [minimal_price] => 24.0000
            [min_price] => 24.0000
            [max_price] => 24.0000
            [tier_price] => 
            [news_from_date] => 
        )

    [5] => Array
        (
            [entity_id] => 1483
            [attribute_set_id] => 16
            [type_id] => configurable
            [sku] => WS07
            [has_options] => 1
            [required_options] => 0
            [created_at] => 2019-04-25 09:31:14
            [updated_at] => 2019-04-25 09:31:14
            [cat_index_position] => 0
            [price] => 42.0000
            [tax_class_id] => 2
            [final_price] => 42.0000
            [minimal_price] => 42.0000
            [min_price] => 42.0000
            [max_price] => 42.0000
            [tier_price] => 
            [news_from_date] => 
        )

    [6] => Array
        (
            [entity_id] => 1958
            [attribute_set_id] => 17
            [type_id] => configurable
            [sku] => WSH03
            [has_options] => 1
            [required_options] => 0
            [created_at] => 2019-04-25 09:31:47
            [updated_at] => 2019-04-25 09:31:47
            [cat_index_position] => 0
            [price] => 50.0000
            [tax_class_id] => 2
            [final_price] => 50.0000
            [minimal_price] => 50.0000
            [min_price] => 50.0000
            [max_price] => 50.0000
            [tier_price] => 
            [news_from_date] => 
        )

    [7] => Array
        (
            [entity_id] => 19
            [attribute_set_id] => 18
            [type_id] => simple
            [sku] => 24-UG02
            [has_options] => 0
            [required_options] => 0
            [created_at] => 2019-04-25 09:29:08
            [updated_at] => 2019-04-25 09:29:08
            [cat_index_position] => 0
            [price] => 16.0000
            [tax_class_id] => 2
            [final_price] => 16.0000
            [minimal_price] => 16.0000
            [min_price] => 16.0000
            [max_price] => 16.0000
            [tier_price] => 
            [news_from_date] => 
        )

    [8] => Array
        (
            [entity_id] => 213
            [attribute_set_id] => 16
            [type_id] => configurable
            [sku] => MH10
            [has_options] => 1
            [required_options] => 0
            [created_at] => 2019-04-25 09:29:51
            [updated_at] => 2019-04-25 09:29:51
            [cat_index_position] => 0
            [price] => 62.0000
            [tax_class_id] => 2
            [final_price] => 62.0000
            [minimal_price] => 62.0000
            [min_price] => 62.0000
            [max_price] => 62.0000
            [tier_price] => 
            [news_from_date] => 
        )

    [9] => Array
        (
            [entity_id] => 695
            [attribute_set_id] => 16
            [type_id] => configurable
            [sku] => MT06
            [has_options] => 1
            [required_options] => 0
            [created_at] => 2019-04-25 09:30:24
            [updated_at] => 2019-04-25 09:30:24
            [cat_index_position] => 0
            [price] => 28.0000
            [tax_class_id] => 2
            [final_price] => 28.0000
            [minimal_price] => 28.0000
            [min_price] => 28.0000
            [max_price] => 28.0000
            [tier_price] => 
            [news_from_date] => 
        )

)

Note: remove generated/* and clear cache

Sohel Rana
  • 35,846
  • 3
  • 72
  • 90
  • Thanks for your answer, Please let me know how to get full product data in this collection, as currently it showing limited product information. – Purushotam Sharma May 01 '19 at 07:06
0

As you are getting the products data in $collection->getData();

For an alternative approach, you can do in newproduct() method like:

$items = $collection->getData();
foreach($items ad $item) {
    $product = $this->productRepository->getById($item['entity_id'], false, $this->_storeManager->getStore()->getId());
    $attributes = $product->getAttributes();
    foreach($attributes as $a)
    {
        $items['extra_attr'][] = $a->getName();
    }
}

return $items;

Note: add the dependency for $this->_storeManager

For standard approach you have to implement the getList() of product repository with SearchCriteriaInterface.

See here

Suman Singh
  • 1,007
  • 2
  • 10
  • 22