wc-api-java icon indicating copy to clipboard operation
wc-api-java copied to clipboard

woocommerce get products gets only first 100.

Open yilmazchef opened this issue 5 years ago • 3 comments

Dear Coder,

Firstly, I would like to thank you for providing such useful library. I have been developing a microservice-based application and using your library multiple times.

When I use the code below:

    Map<String, String> params = new HashMap<>();
    params.put("per_page", "100");
    params.put("offset", "0");
    List<Map<String, Object>> productsMap = wooCommerce.getAll(EndpointBaseType.PRODUCTS.getValue(), params);

Can you please help me to get all the products as Map<String, Object> because I will need to collect all the data from stores.

Thank you very much in advance.

Best regards,

Yilmaz.

yilmazchef avatar Jan 30 '20 09:01 yilmazchef

Hi Yilmaz, if you are using WC v3 try with the following params:

params.put("page", "1");
params.put("per_page", String.valueOf(Integer.MAX_VALUE));

Read more on WC Rest API Docs: http://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-products

Best regards, Oleksandr Mandryk

omandryk avatar Jan 31 '20 07:01 omandryk

Hello Oleksandr,

I have tried params.put("page", "1"); params.put("per_page", String.valueOf(Integer.MAX_VALUE));

however, I received an error..

Is there any other option.

I have coded another solution, I get data 100 products per page, and trying to cache them.

but it would be amazing if I could get all data..

yilmazchef avatar Mar 23 '20 16:03 yilmazchef

To get all products you have to work with page...

import java.util.List; import java.util.ArrayList; import java.util.HashMap; import java.util.Map;

import com.icoderman.woocommerce.ApiVersionType; import com.icoderman.woocommerce.EndpointBaseType; import com.icoderman.woocommerce.WooCommerce; import com.icoderman.woocommerce.WooCommerceAPI; import com.icoderman.woocommerce.oauth.OAuthConfig;

public class Test {

public static void main(String[] args) {
	String url = "http://example.com";
	String ck = "customer_key_from_your_woocommerce_page";
	String cs = "customer_secret_from_your_woocommerce_page";
	
	Map<String, String> options = new HashMap<String, String>();
	OAuthConfig config = new OAuthConfig(url, ck, cs);
	WooCommerce woo = new WooCommerceAPI(config, ApiVersionType.V3);

	List<?> temp;
	List<HashMap<?, ?>> productsTmp = new ArrayList<HashMap<?, ?>>();

	int perPage = 100;
	int page = 1;
	boolean end = false;

	options.put("page", String.valueOf(page));
	options.put("per_page", String.valueOf(perPage));

	while(!end) {			
		temp = woo.getAll(EndpointBaseType.PRODUCTS.getValue(), options);
			
		if(!temp.isEmpty()) {
			for(int i = 0; i < temp.size(); i++) {
				productsTmp.add( (HashMap<?, ?>) temp.get(i) );
			}
			options.put("page", String.valueOf(++page));
		}
		else {
			end = true;
		}
	}
}

}

craftedsro avatar Apr 07 '21 09:04 craftedsro