Create Custom API in Magento 2

Today I’d like to help you through the process of creating Custom API in Magento 2.

At first, we must create the primary files of a module and I would create module under Kaushik name space and call it CustomApi.

File – app/code/Kaushik/CustomApi/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="Kaushik_CustomApi" setup_version="1.0.0" />
</config>

 

File – app/code/Kaushik/CustomApi/registration.php

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

 

File – app/code/Kaushik/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/kaushik-customapi/post">
        <service class="Kaushik\CustomApi\Api\PostManagementInterface" method="getPost"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

 

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

 

File – app/code/Kaushik/CustomApi/Model/PostManagement.php

<?php 
namespace Kaushik\CustomApi\Model;
 
class PostManagement {

    /**
     * {@inheritdoc}
     */
    public function getPost($param)
    {
        return 'api GET return the $param ' . $param;
    }
}

 

File – app/code/Kaushik/CustomApi/Api/PostManagementInterface.php

<?php 
namespace Kaushik\CustomApi\Api;
 
interface PostManagementInterface {

    /**
     * GET for Post api
     * @param string $param
     * @return string
     */
    public function getPost($param);
}

 

That’s all. We’ve just created custom API and now it’s ready to use.

Leave a Reply