Magento 2 – Get Latest Products REST API

apimagento2rest

How can I get latest products as a REST API to display in mobile application home screen ?

Best Answer

You can retrieve latest N products with the Magento 2 API or Repository

Use API call (from javascript widget):

GET http://<magento_host>/rest/V1/products?

And pass your search criteria as an argument.

searchCriteria[sortOrders][0][field]=updated_at
searchCriteria[pageSize]=10

The full request :

GET http://<magento_host>/rest/V1/products?searchCriteria[sortOrders][0][field]=updated_at&searchCriteria[pageSize]=10

The documentation: http://devdocs.magento.com/guides/v2.1/howdoi/webapi/search-criteria.html

This prevents to manage the logic part which may change in the future Magento 2 release.

Use Repository in you template:

\Magento\Catalog\Api\ProductRepositoryInterface::getList

The complete code :

use Magento\Catalog\Api\ProductRepositoryInterface as ProductRepository;
use Magento\Framework\Api\SortOrder as SortOrder;

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

public function __construct(
    ProductRepository $productRepository,
) {
    $this->productRepository = $productRepository;
}


public function getLatestProducts($limit)
{
    /** @var \Magento\Framework\Api\Search\FilterGroup $searchCriteriaGroup */
    $searchCriteriaGroup = $objectManager->create('Magento\Framework\Api\Search\FilterGroup');
    /** @var \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria */

    $sortOrder = $objectManager->create('Magento\Framework\Api\SortOrder');
    $sortOrder->setField('updated_at');
    $sortOrder->setDirection(SortOrder::SORT_DESC)

    $searchCriteria = $objectManager->create('Magento\Framework\Api\SearchCriteriaInterface');
    $searchCriteria->setFilterGroups([$searchCriteriaGroup]);
    $searchCriteria->setPageSize($limit);
    $searchCriteria->setSortOrders([$sortOrder]);

    return $this->productRepository()->getList($searchCriteria)->getItems();
}

And use dependancy injection to avoid objectManager

Related Topic