Sunday, July 10, 2011

Getting product list by category from magento web service


Never thought that in Magento Community Edition 1.5, retrieving product list by category via a web service function could be such a pain.

Let me explain ...

In Magento, you can assign a product to categories.

A product can also have what in Magento's lingo is called an 'attribute set'.



To get products by category, you use web service function catalog_category.assignedProducts. For example, to get products under category id 44 in store 1, use:


$responseInfo = $proxy->call($sessionId, 'catalog_category.assignedProducts', array(44, 1));

Notice that the category id and store id are passed in an array.

A major drawback with this function is that it has no filter options for pagination purposes. So one can't query for items 30 to 40 for a given category id. Strange omission indeed ...




Function catalog_product.list however allows some sort of workaround when it comes to pagination. However, it does not return products based on their category, it uses 'attribute set' instead. Bummer ...

Here is an example usage of this web service function. In the following, we are fetching records which have 'attribute set' 49 and id between 44 to 48.


$filters = array(
'type_id' => array( '=' => 'simple' ),
// // Fetch products which belong to a certain 'attribute set' NOT category.
'set' => array('=' => 49),
// // Fetch products from id 44 to 48, inclusive. Could be used for pagination I guess ...
'product_id' => array('in' => range(44,48)),
// // Fetch active products only
'status' => array('=' => 1)
);
$responseInfo = $proxy->call($sessionId, 'catalog_product.list', array($filters));


catalog_category.assignedProducts could be the prefect function to fetch products by category as this is how most stores display their wares, not using Magento's 'attribute set'. Unfortunately this function is rather spartan and has no filter options unlike catalog_product.list.

A somewhat inelegant workaround to achieve pagination using catalog_category.assignedProducts is by retrieving all products under a specified category and iterate manually to get the range of products which we want to display. IMHO, this may not work so well should the number of items under said category is huge.