To create a custom API in Magento 2, follow these steps:
Create a module by creating a registration.php
file in the app/code
directory and adding the following code:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Vendor_Module',
__DIR__
);
Create a module.xml
file in the app/code/Vendor/Module/etc
directory and add the following code:
<?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="Vendor_Module" setup_version="1.0.0">
<sequence>
<module name="Magento_Webapi"/>
</sequence>
</module>
</config>
Create a webapi.xml
file in the app/code/Vendor/Module/etc/webapi_rest
directory and add the following code:
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi_rest.xsd">
<route url="/V1/custom/hello" method="GET">
<service class="Vendor\Module\Api\HelloInterface" method="sayHello"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>
Create the HelloInterface
file in the app/code/Vendor/Module/Api
directory and add the following code:
<?php
namespace Vendor\Module\Api;
/**
* Hello API interface.
*/
interface HelloInterface
{
/**
* Say hello.
*
* @param string $name
* @return string Greeting message with customer name.
*/
public function sayHello($name);
}
Create the Hello
file in the app/code/Vendor/Module/Model/Hello
directory and add the following code:
<?php
namespace Vendor\Module\Model\Hello;
use Vendor\Module\Api\HelloInterface;
/**
* Hello model.
*/
class Hello implements HelloInterface
{
/**
* Say hello.
*
* @param string $name
* @return string Greeting message with customer name.
*/
public function sayHello($name)
{
return "Hello, $name!";
}
}
Run the following command to enable the module:
php bin/magento module:enable Vendor_Module
php bin/magento setup:upgrade
php bin/magento setup:di:compile
… and that’s it! Your custom API is now accessible on https://www.example.com/V1/custom/hello