I need to find categories by name using Magento 2 rest api.
I use /all/V1/categories
and filters but I can't get it to work.
Here's the code:
$url = "https://*******/index.php/rest";
$token_url= $url."/V1/integration/admin/token";
$ch = curl_init();
$data = array("username" => USERNAME, "password" => PASSWORD);
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
$token = curl_exec($ch);
$adminToken= json_decode($token);
$headers = array('Content-Type:application/json','Authorization:Bearer '.$adminToken);
$ch = curl_init();
$apiUrl = $url."/all/V1/categories";
$data = [
"searchCriteria" => [
"filterGroups" => [
"filters" => [
"fieldName" => "category",
"value" => 'CATEGORY NAME',
"condition_type" => 'eq'
]
]
],
];
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$response = json_decode($response, TRUE);
curl_close($ch);
This is the error that appears after launching the code:
array:3 [▼ "message" => ""%fieldName" is required." "parameters" => array:1 [▼ "fieldName" => "category" ]
You can get categories by name with Magento 2 rest api by adding search criteria to endpoint rest/all/V1/categories/list
. The request to api should look like this:
https://website.com/rest/all/V1/categories/list?searchCriteria%5BfilterGroups%5D%5B0%5D%5Bfilters%5D%5B0%5D%5Bfield%5D=name&searchCriteria%5BfilterGroups%5D%5B0%5D%5Bfilters%5D%5B0%5D%5Bcondition_type%5D=eq&searchCriteria%5BfilterGroups%5D%5B0%5D%5Bfilters%5D%5B0%5D%5Bvalue%5D=category_name
Replace website.com
with the url of your website and category_name
with the search term for category.
If the search string also should match part of the category name, you can use like
instead of eq
.
For more information, refer to: https://devdocs.magento.com/guides/v2.4/rest/performing-searches.html