Home > Software engineering >  How Do I Get the Magento API 2 Product By ID (Not SKU)?
How Do I Get the Magento API 2 Product By ID (Not SKU)?

Time:01-28

Use-case:

When creating a product, it is my understanding that a key/value pair of id is required for all product types for the HTTP POST request into the Magento API Endpoint /pub/rest/default/V1/products.

Issue:

However, as I've experienced, I can overwrite products when using the same id. Thusly, I would like to check whether the id exists in Magento before using it.

Request:

Which endpoint can I use to query to see whether an id exists? Looking at the Docs I couldn't see anywhere to support this requirement.

CodePudding user response:

In the docs, an id of 0 is used. If an id is not provided, it will be created and returned in the response.

The id should not be specified for a new product, though, since it's an auto-generated field. Your unique identifier for a product should be sku. To confirm that a SKU doesn't exist, you could call https://adobe-commerce.redoc.ly/2.4.5-admin/tag/productssku#operation/GetV1ProductsSku. This endpoint will also return the id for the product.

Having a way to uniquely identify your product before adding/updating is pretty important, but if you want to do indiscriminate adds, you can just call that endpoint you reference but either use an id of 0 or don't include id at all.

CodePudding user response:

Search endpoint can be used to achieve what you need. Example request URL would look like this:

http://localhost/rest/all/V1/products?searchCriteria[filterGroups][0][filters][0][field]=entity_id&searchCriteria[filterGroups][0][filters][0][value]=<id>

Note that the store code (all) might differ.

See Magento docs for more info.

  • Related