Magento 2 Create Custom Rest API

Hello Guys! 👋

In this blog, we learn how to create custom rest API calls.

The REST API is a set of functions that call from request and response using the HTTP response.

Magento 2 has a much-predefined REST API but in custom development, we need to create a custom REST API in our system.

So this blog helps you create a custom REST API.

STEP 1: Add webapi.xml in following path.
app\code\Vendor\Extension\etc
<?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/customapi/">
        <service class="Vendor\Extension\Api\CustomapiInterface" method="getData"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

STEP 2: Add CustomapiInterface.php in following path
app\code\Vendor\Extension\Api
<?php
namespace Vendor\Extension\Api;

interface CustomapiInterface
{
    /**
     * GET for Post api
     * @param string $data
     * @return string
     */
    public function getData($data);
}

STEP 3: Add di.xml in following path
app\code\Vendor\Extension\etc
<?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="Vendor\Extension\Api\CustomapiInterface" type="Vendor\Extension\Model\Api\Customapi"/>
</config>

STEP 4: Now add Customapi.php in following path
app\code\Vendor\Extension\Model\Api
<?php
namespace Vendor\Extension\Model\Api;

class Customapi
{
    protected $json;

    public function __construct(
        \Magento\Framework\Serialize\Serializer\Json $json
    ) {
        $this->json = $json;
    }

    /**
     * @inheritdoc
     */
    public function getData($data)
    {
        $response = ['success' => false];
        try {
            // your custom code
            $response = ['success' => true, 'message' => $data];
        } catch (\Exception $e) {
            $response = ['success' => false, 'message' => $e->getMessage()];
        }
        $returnArray = $this->json->serialize($response);
        return $returnArray;
    }
}

Hope! It will help you

Thank you 😊

How useful was this post?

Click on a star to rate it!

Average rating 4.8 / 5. Vote count: 18

No votes so far! Be the first to rate this post.

Leave a Reply

Your email address will not be published. Required fields are marked *