Custom API for Magento 2

Manifest Desires

Billionaire Brain Wave

The Billionaire Brain Wave

The Divine Praye

The Divine Prayer

The Genius Wave

The Genius Wave

Wealth DNA Code

Wealth DNA Code

Custom API for Magento 2

Custom API for Magento 2

API stands for Application Programming Interface which allow you access the data from an application.

Two kinds of the web APIs:
REST (Representational State Transfer)
SOAP (Simple Object Access Protocol).

How to create custom API Module:

Magento 2. To generate access token inside for your Magento 2 store navigate to System -> Extensions -> Integrations and generate it.

custom API

etc/module.xml

<?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=”Latestblog_Hello” setup_version=”1.0.0″ />
</config>

Registration – registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
‘Latestblog_Hello’,
__DIR__
);

Web API configuration – 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 url=”/V1/hello/name/:name” method=”GET”>
<service class=”Latestblog\Hello\Api\HelloInterface” method=”name”/>
<resources>
<resource ref=”anonymous”/>
</resources>
</route>
</routes>

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=”Latestblog\Hello\Api\HelloInterface”
type=”Latestblog\Hello\Model\Hello” />
</config>

Interface – Api/HelloInterface.php

<?php
namespace Latestblog\Hello\Api;

interface HelloInterface
{
/**
* Returns greeting message to user
*
* @api
* @param string $name Users name.
* @return string Greeting message with users name.
*/
public function name($name);
}

Model – Model/Hello.php

<?php
namespace Latestblog\Hello\Model;
use Latestblog\Hello\Api\HelloInterface;

class Hello implements HelloInterface
{
/**
* Returns greeting message to user
*
* @api
* @param string $name Users name.
* @return string Greeting message with users name.
*/
public function name($name) {
return “Hello, ” . $name;
}
}
By using postman check data accordingly
To test REST you can go to http://{domain_name}/rest/V1/{method}/{attribute}/{value}.

Manifest Desires-Click Here