REST stands for representational state transfer and API stands for an application programming interface. REST API is basically used for performing some operations and getting responses based on the request using the HTTP protocol. Magento provides a huge list of REST APIs which you can check here. Another approach to check and play with the existing APIs in the Magento system is Swagger. You can access Swagger by any browser and the URL will be your website's baseUrl/swagger.
Now let's see how we can add a new custom API in Magento. Let's learn this by creating a custom API to get all the store configurations using API.
Step - 1: Create a webApi.xml file and add the route for your API
<?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 method="GET" url="/V1/custom/storeConfigurations/">
<service class="MageInsight\Common\Api\StoreConfigurationInterface" method="getConfigs"/>
<resources>
<resource ref="Magento_Backend::store"/>
</resources>
</route>
</routes>
Here you can see, that the API endpoint will be custom/storeConfigurations and the method will be the GET method.
Step - 2: Create an Interface for your API
<?php
namespace MageInsight\Common\Api;
interface StoreConfigurationInterface
{
/**
* Get store configurations
* @param string $path
* @return string|array
*/
public function getConfigs($path);
}
While creating an interface, take care of the below points:
- Add the method name here with the same name declared in the webApi.xml file.
- Add proper comments for the function, because that defines the parameter & response datatype. And method description will be shown in the swagger.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<preference for="MageInsight\Common\Api\StoreConfigurationInterface" type="MageInsight\Common\Model\StoreConfiguration"/>
</config>
<?php
namespace MageInsight\Common\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use function Safe\json_encode;
class StoreConfiguration
{
protected $scopeConfig;
protected $jsonFactory;
public function __construct(
ScopeConfigInterface $scopeConfig,
JsonFactory $jsonFactory
){
$this->scopeConfig = $scopeConfig;
$this->jsonFactory = $jsonFactory;
}
/**
* {@inheritdoc}
*/
public function getConfigs($path) {
$config = $this->scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORES, 0);
if (is_string($config)) {
$result[] = ["value" => (int) $config];
return $result;
}
return [$config];
}
}
After this, the API can be tested using swagger or postman.
Comments
Post a Comment