How to Create a Custom Rest API in Magento 2?

Today, we’re going to teach you guys how to create a REST API in Magento 2.

REST API basically helps to define a set of functions to perform requests and get responses using the HTTP protocol.

By default, Magento 2 already comes with certain predefined REST APIs such as Order API, Product API, and Customer API using which you can virtually control everything happening on your Magento 2 store.

But, even though Magento 2 provides all these REST APIs, they’re not enough when you’re using custom data and their values.

So, to manage your custom data and fields, you’ll have to create a custom REST API.

In this post, we’re going to show you exactly how to create a custom REST API in your Magento 2 store.

Step-by-Step Process to Create a Custom REST API in Magento 2

Please follow the below-mentioned steps to learn how to create a Custom REST API in your Magento 2 store.

Step - 1

First of all, create a module.xml file in the app/code/MageDelight/CustomApi/etc/ folder and paste 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="MageDelight_CustomApi" setup_version="1.0.0" />
</config>

Step - 2

After that, create a registration.php file in the app/code/MageDelight/CustomApi/ and paste the following code.

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

Step - 3

Next, create a webapi.xml file in the app/code/MageDelight/CustomApi/etc/ folder and paste the following code.

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
    <route method="POST" url="/V1/custom/custom-api/">
        <service class="MageDelight\CustomApi\Api\CustomInterface" method="getPost"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Step - 4

Now, create a di.xml file in the app/code/MageDelight/CustomApi/etc/ folder and paste the following code.

<?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="MageDelight\CustomApi\Api\CustomInterface" type="MageDelight\CustomApi\Model\Api\Custom"/>
</config>

Step - 5

After that, create a CustomInterface.php file in the path app/code/MageDelight/CustomApi/Api/ folder and paste the following code.

<?php
namespace MageDelight\CustomApi\Api;
interface CustomInterface
{
    /**
     * GET for Post api
     * @param string $value
     * @return string
     */
    public function getPost($value);
}

Step - 6

Next, create a Custom.php file in the app/code/MageDelight/CustomApi/Model/Api/ folder and paste the following code.

<?php
namespace MageDelight\CustomApi\Model\Api;
use Psr\Log\LoggerInterface;
class Custom
{
    protected $logger;
    public function __construct(
        LoggerInterface $logger
    )
    {
        $this->logger = $logger;
    }
    /**
     * @inheritdoc
     */
    public function getPost($value)
    {
        $response = ['success' => false];
        try {
            // Your Code here
            $response = ['success' => true, 'message' => $value];
        } catch (\Exception $e) {
            $response = ['success' => false, 'message' => $e->getMessage()];
            $this->logger->info($e->getMessage());
        }
        $returnArray = json_encode($response);
        return $returnArray; 
   }
}

Step- 7

Finally, run the setup upgrade and deploy commands in CLI, and your custom REST API is finally created in your Magento 2 store.

You can verify the custom REST API by using [webiste/domain]/swagger

Custom Rest API

Also read: How to Manage Index and Cache Management Using Magento 2 REST API?

Conclusion

And that’s about it!

This is the easiest way to create a Custom REST API in Magento 2.

And if you need our professional assistance with Magento Web Development, feel free to reach out to us anytime.