To search for a product in Magento 2 using the API, you can use the catalogProductRepositoryV1
API. Here’s an example of how to search for a product by name or SKU using this API:
// Initialize the API client
$baseUrl = 'https://example.com/';
$token = 'your_api_token';
$httpClient = new \GuzzleHttp\Client(['base_uri' => $baseUrl]);
$apiClient = new \Magento\Framework\Webapi\Rest\Client($httpClient);
$apiClient->setToken($token);
// Search for products by name
$searchCriteria = [
'searchCriteria' => [
'filterGroups' => [
[
'filters' => [
[
'field' => 'name',
'value' => '%product_name%',
'conditionType' => 'like'
]
]
]
]
]
];
$products = $apiClient->catalogProductRepositoryV1()->getList($searchCriteria)->getItems();
// Search for products by SKU
$searchCriteria = [
'searchCriteria' => [
'filterGroups' => [
[
'filters' => [
[
'field' => 'sku',
'value' => '%product_sku%',
'conditionType' => 'like'
]
]
]
]
]
];
$products = $apiClient->catalogProductRepositoryV1()->getList($searchCriteria)->getItems();
In the above example, you will need to replace https://example.com/
with your Magento 2 store’s base URL, and your_api_token
with a valid API token for your Magento 2 store.
You can also replace %product_name%
or %product_sku%
with the actual name or SKU you want to search for. The like
condition type is used to perform a partial match search. If you want to perform an exact match search, you can use the eq
condition type instead.
The getList()
method returns a Magento\Catalog\Api\Data\ProductSearchResultsInterface
object, which contains an array of Magento\Catalog\Api\Data\ProductInterface
objects representing the search results. You can then iterate over this array to access the details of each product.
https://example.com/rest/V1/products?searchCriteria[filterGroups][0][filters][0][field]=name&searchCriteria[filterGroups][0][filters][0][value]=%product_name%&searchCriteria[filterGroups][0][filters][0][conditionType]=like
https://example.com/rest/V1/products?searchCriteria[filterGroups][0][filters][0][field]=sku&searchCriteria[filterGroups][0][filters][0][value]=%product_sku%&searchCriteria[filterGroups][0][filters][0][conditionType]=like
Replace https://example.com/
with your Magento 2 store’s base URL, and replace %product_name%
or %product_sku%
with the actual name or SKU you want to search for.
This API endpoint uses the same searchCriteria
format as in the previous PHP example. The endpoint returns a JSON object containing an array of product objects that match the search criteria.
You will need to authenticate the API request with a valid API token in the request header. You can add an Authorization: Bearer your_api_token
header to the request, replacing your_api_token
with a valid API token for your Magento 2 store.