In Magento2, API plays a vital role to create a shopping app, integrate with CRM (Customer Relationship Management) or ERP (Enterprise Resource Planning) or CMS.
Magento 2 has very good API support. It supports both REST (Representational State Transfer) and SOAP (Simple Object Access Protocol).
But sometimes we need to create our own custom API for doing stuff more easily. Here I will try to show how to create our own custom REST API.
Creating a custom API is relatively easy in Magento 2 than Magento 1. Please follow the steps in the below:
First, create a basic module by creating etc/module.xml, registration.php, composer.json file. Then you have to add REST API feature to this module.
Add webapi.xml file to declare the API URL or API endpoint, service class, and methods.
app/code/Milandev/SimpleAPI/etc/webapi.xml
<?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/milandev-simpleapi/product/:sku">
<service class="MilanDev\SimpleAPI\Api\ProductManagementInterface" method="getProduct"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>
Add API class.
app/code/Milandev/SimpleAPI/Model/ProductManagement.php
<?php
namespace MilanDev\SimpleAPI\Model;
class ProductManagement implements \MilanDev\SimpleAPI\Api\ProductManagementInterface
{
/**
* {@inheritdoc}
*/
public function getProduct($sku)
{
// add your logic
return $sku;
}
}
Add API interface.
app/code/Milandev/SimpleAPI/Api/ProductManagementInterface.php.
<?php
namespace MilanDev\SimpleAPI\Api;
interface ProductManagementInterface
{
/**
* GET for product api
* @param string $sku
* @return string
*/
public function getProduct($sku);
}
Add dependency class in the di.xml.
app/code/Milandev/SimpleAPI/etc/di.xml
<?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="MilanDev\SimpleAPI\Api\ProductManagementInterface" type="MilanDev\SimpleAPI\Model\ProductManagement"/>
</config>
Test the API using rest-client by following the URL structure. http://exmaple.com/index.php/rest/V1/milandev-simpleapi/product/sku
This is just a skeleton of a custom REST API module. You need to add your own logic. You can extend this module as you need by adding endpoints, interfaces, classes, methods, and logics. Happy Coding!