Custom API for Magento 2

How To Create Custom Rest API In Magento 2

Custom api in magento 2 means helping online retailers an Application Programming Interface for the own using. API is a required element to connect among the data if you ask for any program or service from other websites. With API’s, you can easily get all building blocks to initiate a program successfully.

You can test api on http://<yourhost>/swagger

Application Programming Interface allows you to access the data from an application. API can be called middleman between a programmer and an application.

Lets Start

Create and enable a module.

Create a registration.php in app/code/Bay20/CustomApi/ directory.

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Bay20_CustomApi',
    __DIR__
);

Create module.xml in app/code/Bay20/CustomApi/etc/ directory.

<?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="Bay20_CustomApi" setup_version="1.0.0"/>
</config>

After creating these two files, run the command

php bin/magento module:enable Bay20_CustomApi

Web API configuration

app/code/Bay20/CustomApi/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/mageplaza-helloworld/post">
		<service class="Bay20\CustomApi\Api\PostManagementInterface" method="getPost"/>
		<resources>
			<resource ref="anonymous"/>
		</resources>
	</route>
</routes>

Resource tag defines what resources user needs to have to be able to access this api call.

Define Interface

In di.xml we define what model will interface call to.

app/code/Bay20/CustomApi/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="Bay20\CustomApi\Api\PostManagementInterface" 
    type="Bay20\CustomApi\Model\PostManagement"/>
</config>

Interface

app/code/Bay20/CustomApi/Api/PostManagementInterface.php

<?php 
namespace Bay20\CustomApi\Api;

interface PostManagementInterface {

	/**
	 * GET for Post api
	 * @param string $param
	 * @return string
	 */

	public function getPost($param);
}

Model

app/code/Bay20/CustomApi/Model/PostManagement.php

<?php 
namespace Bay20\CustomApi\Model;
class PostManagement 
{
	public function getPost($param)
	{
		return 'api GET return the $param ' . $param;
	}
}

Within model we add our functionality that will be executed by call to API method.

Conclusion:

With the help of above files, you can create a custom api in magento 2