In this post, we will walk you through the process of creating an API response in Magento 2 that retrieves the only SKU and quantity of products. By following these steps and using the provided code snippets, you’ll be able to streamline your development workflow and obtain specific product information for your Magento store.
Table of Contents
Set up the API Integration
Log in to your Magento 2 admin panel and navigate to System > Integrations. Click on “Add New Integration” and fill in the necessary details. Enable the “Resource Access” settings for Products.
Create a module.xml
In your Magento 2 codebase, create a new module define the custom API endpoint. The module.xml
file contains metadata and configuration information about the module. It specifies the module name, version, and other relevant details.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Company_ProductApi" setup_version="1.0.0">
<sequence>
<module name="Magento_Catalog"/>
</sequence>
</module>
</config>
Create registration.php
The registration.php
file is used to register the module with Magento 2. It provides autoloading capabilities for the module and ensures that it is properly installed and recognized by the system.
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Company_ProductApi',
__DIR__
);
Create an Interface ProductStockInterface.php
This file defines the interface for the API endpoint. It contains a single method, getApiData()
, which is responsible for retrieving the SKU and quantity data of the products.
namespace Company\ProductApi\Api;
/**
* Interface ProductStockInterface
*/interface ProductStockInterface
{
/**
* get products sku & qty data.
*
* @return array
*/ public function getApiData();
}
Create a Model class ProductStock.php
The ProductStock
class implements the ProductStockInterface
and handles the logic for retrieving the SKU and quantity data. It utilizes the Magento 2 Product Collection and joins it with the Catalog Inventory Stock Item table to fetch the necessary information.
<?php
namespace Company\ProductApi\Model\Api;
/**
* Model class ProductStock
*/class ProductStock implements \Company\ProductApi\Api\ProductStockInterface
{
/**
* @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
*/ protected $productCollection;
/**
* @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollection
*/ public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollection
)
{
$this->productCollection = $productCollection;
}
/**
* get products sku & qty data.
*
* @return array
*/ public function getApiData()
{
$returnArray = [];
try{
$productCollection = $this->productCollection->create()
->addAttributeToSelect('*')
->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->addAttributeToFilter('type_id', \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->joinField(
'qty', 'cataloginventory_stock_item', 'qty', 'product_id=entity_id', '{{table}}.stock_id=1', 'left'
);
foreach ($productCollection as $product) {
$returnArray[] = ["sku" => $product->getSku(), "qty" => $product->getQty()];
}
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$returnArray['error'] = $e->getMessage();
$returnArray['status'] = 0;
} catch (\Exception $e) {
$returnArray['error'] = __('unable to process request');
$returnArray['status'] = 2;
}
return $returnArray;
}
}
Create the di.xml file
The di.xml
file is a Magento 2 configuration file used for dependency injection. It sets up a preference for the ProductStockInterface
, indicating that the ProductStock
class should be used when the interface is requested.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Company\ProductApi\Api\ProductStockInterface" type="Company\ProductApi\Model\Api\ProductStock" />
</config>
Create the webapi.xml file
The webapi.xml
file defines the API route for accessing the SKU and quantity data. It specifies the endpoint URL, /V1/company/products
, and the corresponding service class and method to handle the API request.
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/company/products" method="GET">
<service class="Company\ProductApi\Api\ProductStockInterface" method="getApiData"/>
<resources>
<resource ref="Magento_Catalog::products"/>
</resources>
</route>
</routes>
Test and Validate the API
Use a REST client or any preferred tool such as postman to send requests to the newly created API endpoint. Verify that the response contains the expected product SKU and quantity data. To make any api call you will need an access token. To generate an access token you can follow this article https://learningmagento.com/create-access-token-in-magento/
- Ensure the module is installed: Make sure that the module containing the API implementation is installed and enabled in your Magento 2 instance. You can verify this by checking the list of installed modules in the
app/etc/config.php
file. - Clear the cache: If the module was just installed or enabled, it’s a good practice to clear the cache to ensure that the changes take effect. You can clear the cache by running the following command in the terminal:
php bin/magento cache:clean
- Generate the API documentation: Magento 2 provides a built-in tool called Swagger that generates API documentation. To access the Swagger UI, open a web browser and navigate to
http://<your-magento-url>/swagger
. You should see a list of available APIs, including your custom API endpoint. - Explore the API documentation: In the Swagger UI, locate your custom API endpoint for retrieving SKU and quantity data. Review the available parameters, request/response formats, and any additional details provided in the documentation. This will help you understand how to interact with the API.
- Test the API using an API client: To validate the API and ensure it returns the expected results, you can use an API client tool like Postman or cURL. Construct a GET request to the API endpoint, providing any required parameters, and send the request. Verify that the response contains the SKU and quantity data for the products.
- Validate the response: Check the response data returned by the API against your expectations. Ensure that the SKU and quantity information is accurate and matches the data in your Magento 2 store. If there are any errors or issues, review the code implementation and logs for debugging.
- Test different scenarios: To validate the robustness of the API, test it with various scenarios such as different product types, large product catalogs, and edge cases. Ensure that the API handles these scenarios gracefully and returns the correct data.
- Monitor and analyze performance: Monitor the performance of the API endpoint, including response times and resource consumption. Analyze the performance metrics to identify any potential bottlenecks or areas for optimization. Make necessary adjustments to enhance the API’s performance.
Conclusion
By following the outlined steps and utilizing the provided code snippets, you can easily create an API response in Magento 2 that retrieves the SKU and quantity of products. This custom API can be beneficial for various purposes, such as integrating with external systems or building custom reporting tools. Implementing APIs efficiently can enhance the functionality and flexibility of your Magento store, empowering you to deliver a seamless shopping experience for your customers.