Today, we’re focusing on an essential, yet sometimes overlooked aspect of Magento 2: getting a product by SKU using GraphQL. Understanding how to accurately and efficiently retrieve product details using SKU, or Stock Keeping Unit, is crucial for managing any e-commerce platform.
Whether you are a seasoned developer looking to sharpen your skills or a newbie trying to navigate the exciting world of Magento 2, this article will serve as a handy guide, breaking down the process into easy-to-understand steps.
Contents
Get A Product By SKU With GraphQL
Endpoint: “http(s)://yourdomain.com/graphql”
Method: POST
Syntax: products( search: String filter: ProductFilterInput pageSize: Int currentPage: Int sort: ProductSortInput ): Products
Request example:
{ products( filter: { sku: { like: "24-WB%" } } pageSize: 20 currentPage: 1 sort: { name: DESC } ) { items { sku } filters { name filter_items_count request_var filter_items { label value_string items_count } } } }
Response:
{ "data": { "products": { "total_count": 26, "items": [ { "name": "BUNDLE: Tiny Round \"Design Your Own\" Children's Necklace for Girls (50+ Optional Charms & FREE Engraving)", "sku": "Tiny Round", "price": { "regularPrice": { "amount": { "currency": "USD", "value": 439.78 } } } }], "page_info": { "page_size": 25, "current_page": 1 } } } }
For example:
Then, you write down the endpoint and your request:
After that, you can click run to send a request to the server.
Bonus: Get A Product With REST API
You can use a tool to access the API. In this situation, we will use Postman.
We need to get the access token of the admin user to get a product.
Endpoint: “http(s)://yourdomain.com/rest/V1/integration/admin/token”
Method: POST
Request:
{ "username" : "string", "password" : "string" }
Response: “token” (string)
For example:
In the first step, we get the access token of the admin user to get a product.
Endpoint: “http(s)://yourdomain.com/rest/V1/integration/admin/token”
Method: POST
Request:
{ "username" : "string", "password" : "string" }
Response: “token” (string)
For example:
Now, we have the access token. Let begin to get a product from API.
Endpoint: “http(s)://yourdomain.com/rest/V1/ products/:sku”
Method: GET
Request: sku.
Header: Authorization: Bearer (Token)
Response: token(string)
For example:
You need to check the access token. If it is correct, the API will return Product’s Information.
If the access token is incorrect, the API will return the error message like the following:
This is a process to get a product from REST API.
We hope that this instruction will help you get a product through API easily.