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.


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

<?xml version="1.0"?>
<config xmlns:xsi=""
    <module name="Bay20_CustomApi" setup_version="1.0.0"/>

After creating these two files, run the command

php bin/magento module:enable Bay20_CustomApi

Web API configuration


<?xml version="1.0" ?>
<routes xmlns:xsi="" 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"/>
			<resource ref="anonymous"/>

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.


<?xml version="1.0" ?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
	<preference for="Bay20\CustomApi\Api\PostManagementInterface" 



namespace Bay20\CustomApi\Api;

interface PostManagementInterface {

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

	public function getPost($param);



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.


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

Please contact us at or call us at +91-8800519180 for any support related to Magento 2. You can also visit the Magento2 development page to check the services we offer.