Magento – Magento 2 search using REST APIs

apicurlmagento2PHPrest

I'm getting crazy with PHP curl and query string against Magento 2 REST Api.
I have the following query:

http://mystore/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=10

coping and pasting it in the browser it works fine. If I use PHP and curl like in this example:

$curl = curl_init("http://mystore/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=10");
...
curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => 1,
        ...
    ]);
return curl_exec($curl);

Magento return an "Invalid signature" error.
I found the problem, is the encoding of "&" character, but I tried using urlencode() or htmlentities(), I cannot find a solution. It works only substituting "&" with "& amp;" (without space), but the query is not correctly interpreted. Which is the correct way to send the query string using PHP curl?

Best Answer

Try following way:

$userData = array("username" => "admin", "password" => "admin123");
$ch = curl_init("http://mystore/index.php/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));

$token = curl_exec($ch);

$ch = curl_init("http://mystore/index.php/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=10");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

$result = curl_exec($ch);

$result = json_decode($result, 1);
print_r($result);
Related Topic