0

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

1
  • latest in terms of new ? have you marked that product as a new from admin ? Jul 26, 2017 at 5:41

1 Answer 1

1

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

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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