How To

How to Create Custom REST API in Magento 2?

Today to build a powerful Ecommerce store apart from choosing the right CMS, you also have to integrate and connect some third-party services like payment gateways and delivery partners. However, Magento comes with an interface that lets third-party applications read and write to a system using programming language constructs or statements. And, Magento supports and provides REST and SOAP. You can also create a dynamic REST API documentation set on your server with live data. By default, Magento uses Swagger to display REST APIs for all installed products and allows you to try out the APIs.

Many times it happens that you have to create your custom Rest API in your module to perform some action based on response. You still can use default API features Product API, Order API, Customer data API, etc. These all the APIs have multiple methods like GET, PUT, POST, etc. But if you want to create custom response apart from this you have no option left except creating custom API. So let’s learn how you can create your custom API in Magento 2.
But before we start first we need to generate Access Token for accessing Magento. To generate access token inside for your Magento 2 store simply navigate to System -> Extensions -> Integrations and generate it.

Now, we have to create a custom module by following the below steps.

Steps to Create Custom REST API in Magento 2:

Step 1: Firstly, we need to create a “registration.php” file inside our extension folder on this path.

app\code\Vendor\Extension app\code\Vendor\Extension\etc

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

Step 2: After that, we need to create “Module.xml” file inside the extension etc folder

app\code\Vendor\Extension\etc

<?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="Vendor_Extension" setup_version="1.0.0" schema_version="1.0.0">
    </module>
</config>

Step 3: Now, we have to create one more file “webapi.xml” inside the same etc folder.

app\code\Vendor\Extension\etc

<?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/vender-extension">
        <service class="Vendor\Extension\Api\PostManagementInterface" method="customGetMethod"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>

<!--POST API Start-->
    <route method="POST" url="/V1/vender-extension/post">
<service class="Vendor\Extension\Api\PostManagementInterface" method="customPostMethod"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Step 4: And then, we need to create “di.xml” file in same etc folder of our extension.

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\PostManagementInterface" type="Vendor\Extension\Model\PostManagement"/>
</config>

Step 5: Later, create “PostManagementInterface.php” file inside extensions’s API folder to serve a response.

app\code\Vendor\Extension\Api\

<?php
namespace Vendor\Extension\Api;
interface PostManagementInterface {


    /**
     * GET for Post api
     * @param string $storeid
     * @param string $name
     * @return string
     */
    public function customGetMethod($storeid,$name);

    /**
     * GET for Post api
     * @param string $storeid
     * @param string $name
     * @param string $city
     * @return string
     */
    public function customPostMethod($storeid,$name,$city);

}

Step 6 : Lastly, Create “PostManagement.php” file inside model folder of extension.

app\code\Vendor\Extension\Model

<?php
namespace Vendor\Extension\Model;
use Vendor\Extension\Api\PostManagementInterface;
class PostManagement implements PostManagementInterface
{
    /**
     * {@inheritdoc}
     */    public function customGetMethod($storeid,$name)
    {
        try{
            $response = [
                    'storeid' => $storeid,
                    'name' =>$name
            ];
        }catch(\Exception $e) {
            $response=['error' => $e->getMessage()];
        }

        return json_encode($response);
    }

    /**
     * {@inheritdoc}
     */    public function customPostMethod($storeid,$name,$city)
    {
        try{
            $response = [
                'storeid' => $storeid,
                'name' =>$name,
                'city'=>$city
            ];
        }catch(\Exception $e) {
            $response=['error' => $e->getMessage()];
        }
        return json_encode($response);
    }

}

Now, Go to Admin -> System -> Integrations and Get Access Token value and set authorization value into postman application.

Then, execute

Get Api Url : {base_url}/rest/V1/vender-extension

Post Api Url : {base_url}/rest/V1/vender-extension/post

this URL in postman.

And, you will able to fetch All the Parameter you want to set it.

Get API Response:

Post API Response:

That’s it for today! You have successfully Implemented Custom Rest API in Magento 2 and you are free to customize this code according to your need for fetching data using REST API. Furthermore, You can also refer to this article: Everything You Need to Know About Magento 2 API.

Lastly, if you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends and Let us know if you are facing any issues while implementing this code.
Happy RESTing!

Click to rate this post!
[Total: 18 Average: 4.5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

Recent Posts

Magento 2: How to Add View Button in Admin Grid to Open a View Page in Slide Window

Hello Magento Friends, In Magento 2, customizations to the admin panel can significantly enhance the…

12 hours ago

Magento 2: How to Observe the Multi-shipping Order Creation Event

Hello Magento Friends, Magento 2 provides a robust event-driven architecture that allows developers to observe…

3 days ago

Hyvä Theme FAQs

Hyvä is gradually gaining popularity in this current market, and even 3.5% of Magento websites…

4 days ago

What is Curbside Pickup?

In today’s fast-paced society, where convenience and safety are paramount, curbside pickup has emerged as…

4 days ago

What is a Planogram?

Have you ever observed how complementary and similar items are often displayed together in brick-and-mortar…

4 days ago

Hyvä Checkout – A Real Game Changer

You may be familiar with Hyvä, the frontend theme for Magento 2, which has been…

4 days ago