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

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

11 hours ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

3 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

3 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

4 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

4 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

7 days ago