This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Magento 2 Rest API: What Is It and How to Use It to Create a Custom API Module

Updated on August 29, 2022

9 Min Read
Magento 2 Rest API

The API is built to create integration with other applications quickly and easily. The Magento API allows the developers to create the integration process easier with custom data and less complexity. With rapid changes and saving the developer time, the Magento 2 API structure provides the configurable URL structure, parameters, and predictable responses for creating the integration.

The ecosystem of the Magento API framework purposes to evolve with the web and solve complex problems incorporated in the eCommerce world – such as real-time communication, custom data with endpoints, selling multi-channel products, and much more.

Magento 2 API is a core part of our mission to create integrations with third-party services. All the elements must be configured in the webapi.xml file to configure and understand the web API. To perform robust integrations, Magento 2 API help developers easily customize the structure of API call. In Magento 2, REST API is the most common way for developers to get a response from HTTP protocol but first, let’s understand Magento 2 API and its need.

What Is Magento 2 API?

Magento 2 API framework allows developers to create new services for communicating with other Magento 2 stores and applications. All Magento API supports REST and SOAP web services and is based on CRUD operations (Create, Read, Update, Delete) and a Search Model. First, we need to understand the RESTFul API in Magento, an architectural style for communication between applications with limited resources to the user.

Given the importance of REST API in web apps, It is surprising that many Magento developers ask, What is Magento 2 REST API?

Magento 2 REST API framework first checks whether the call has appropriate authorization to perform the request. The API framework also supports field filtering of API responses to preserve cellular bandwidth.

Developers use Magento 2 REST APIs for a wide range of tasks. For instance, you can create a shopping app and integrate it with your Magento 2 store. You can also build a web app that your employee could use to help customers make purchases. With the help of APIs, you can integrate your Magento 2 store with CRMs, ERPs, or POS systems.

Let’s look at what is Magento 2 REST API entails, how to use it, and how to create a custom REST API in Magento 2 based on the model.

Using Magento 2 REST API

The Magento 2 REST API has a predefined set of functions that the developer will use to perform requests and get responses using the HTTP protocol. But for that, you need to understand the flow to call APIs.

The REST API structure to initiate the HTTP request includes the below elements:

  • An HTTP Header: Determines the authentication
  • HTTP verb: Defines the action to be performed by endpoint such as GET, POST, PUT, and DELETE
  • Endpoint: A uniform resource identifier (URI) for identifying the server, web services, and resource information.
  • Call Payload: Set of input parameters and attributes provided with the request, optional or required.

magento-rest-api
Magento REST API Authentication

At the moment, Magento 2 uses the following three authentication methods described in Magento 2 REST API documentation.

  • Token-Based authentication to authenticate mobile applications.
  • Admins and customers authentication with login credentials.
  • OAuth authentication for third-party applications.

According to the Magento 2 API documentation, these authentication methods can only access the resources assigned. Before getting started with Magento 2 REST API, you need to authenticate the identity of the user and the permissions to access the API. Permissions required to access particular resources are configured in the webapi.xml file. Customers have the same set of permissions for the response. Magento 2 API comes up with the user types with the contained set of permissions, which includes:

User Type

  • Admin or Integration;
  • Customer;
  • Guest User.

Magento 2 API Token-Based Authentication

To make a Magento 2 API call for extracting the desired information, an access token must be the key to access the API.

If you want to use token-based Magento 2 API, you first need to authenticate and get the token from Magento 2. Then, you will have to pass it in the header of every request you perform.

To get started with the Magento 2 REST API using token-based authentication, you will need to verify that the caller initiating the request is authorized for the call. I will also use this REST API for this tutorial to create a simple product and the custom Magento REST API module.

Getting the Admin Authorization Token

As I mentioned earlier, I will authenticate REST API through Token authentication. This means I will pass an admin username and password in the initial connection and receive the token. This token will be saved and later passed in the header for further calls.

If you don’t want to use the admin username and password, you can create another new user account with associated resources for web services only.

Create a Web Services User on Magento Admin

If the authentication you use is token-based, select System → Permission → All Users → Add New User. Creating the new user in the Admin is unnecessary with the two remaining authentications.

Endpoint

POST <host>/rest/<store_code>/V1/integration/admin/token

Example

http://magento-91647-257956.cloudwaysapps.com/index.php/rest/V1/integration/admin/token

Headers

Content-Type application/json

Payload

{

  "username": "[email protected]",

  "password": "FBxftRsYrqN6Ka"

}

Response

Magento returns the admin’s access token.

magento-rest-api-auth-code

In the above API, I passed the username and password with the API URL to authenticate the REST API and then saved this token for further use. Later you need to specify this token in the authorization header of every call that requires admin permissions.

Getting the Customer Access Token by Rest API

Magento 2 REST API can be authenticated by customer user type, as mentioned earlier. Just like Magento Admin Token to process the request related to the customer’s activities, such as editing account information, the Customer Access Token is required.

Developers can use customer-generated tokens for implementing the customer-level functionality while developing the application. To get this, the caller must pass the username and password to the request.

Endpoint

POST <host>/rest/<store_code>/V1/integration/customer/token

Example

http://magento-91647-257956.cloudwaysapps.com/index.php/rest/V1/integration/customer/token

Headers

Content-Type application/json

Payload

{

  "username": “[email protected]”,

  "password": "Pa$$w0rd!"

}

magento-rest-api-customer-token

Response

The response will return the customer access token from Magento 2.

Getting the Anonymous Guest User Rest API

Token-based authentication act as a security layer for overcoming the vulnerabilities attacks in any application by granting permissions. The Magento 2 REST API framework for the guest user is configured for the open-source resources that didn’t authenticate the permissions to access the API request call.

By default, in Magento 2, the list of unauthenticated endpoints is accessed by the guest users with anonymous permissions. Developers can disable this privilege from the Admin Panel, log in to the admin, and navigate to the Stores → Settings → Configuration → Services → Magento Web API → Web API Security. Then select Yes from the Allow Anonymous Guest Access menu.

magento-rest-api-access-grant

OAuth Token REST API Magento 2

Magento 2 Rest API integrates with third-party applications or services using the OAuth token authorization. The OAuth authentication in Magento process the integration associated with the resources required.

The third-party service is configured in Magento by selecting System → Extensions → Integrations. The configuration includes a callback URL and an identity link URL. The callback URL specifies where OAuth credentials can be sent when using OAuth for token exchange. The identity link points to the login page of the third-party application that is integrating with Commerce.

magento-rest-api-integeration

Call Magento REST API

This section will explain how to call a default Magento REST API to create a product.

Create a Simple Product

Endpoint

POST <host>/rest/V1/products

Example

http://magento-761105-2575467.cloudwaysapps.com/index.php/rest/V1/products

Header Authorization

In the Header Authorization

Authorization

Bearer your token

Token

Generated by the admin token Rest API

Content-Type

application/json

Payload

Enter the payload into the body section

{

  "product": {

    "sku": "VBP_001",

    "name": "Vintage Backpack",

    "attribute_set_id": 9,

    "price": 32,

    "status": 1,

    "visibility": 1,

    "type_id": "simple",

    "weight": "30",

    "extension_attributes": {

     "category_links": [

     {

     "position": 0,

     "category_id": "11"

     },

     {

     "position": 1,

     "category_id": "12"

     },

     {

     "position": 2,

     "category_id": "16"

     }

     ],

     "stock_item": {

     "qty": "100",

     "is_in_stock": true

     }

    },

    "custom_attributes": [

     {

     "attribute_code": "description",

     "value": "Vintage Backpack is a heavyweight washed cotton canvas backpack with a large main compartment, a front pocket, and two side pockets."

     },

     {

     "attribute_code": "tax_class_id",

     "value": "2"

     },

     {

     "attribute_code": "color",

     "value": "42"

     },

     {

     "attribute_code": "size",

     "value": "20"

     }

    ]

  }

}

Response

{
    "id": 2047,
    "sku": "VBP_001",
    "name": "Vintage Backpack",
    "attribute_set_id": 9,
    "price": 32,
    "status": 1,
    "visibility": 1,
    "type_id": "simple",
    "created_at": "2022-07-04 22:02:50",
    "updated_at": "2022-07-04 22:03:02",
    "weight": 30,
    "extension_attributes": {
        "website_ids": [
            1
        ],
        "category_links": [
            {
                "position": 0,
                "category_id": "11"
            },
            {
                "position": 1,
                "category_id": "12"
            },
            {
                "position": 2,
                "category_id": "16"
            }
        ],
        "stock_item": {
            "item_id": 2047,
            "product_id": 2047,
            "stock_id": 1,
            "qty": 100,
            "is_in_stock": true,
            "is_qty_decimal": false,
            "show_default_notification_message": false,
            "use_config_min_qty": true,
            "min_qty": 0,
            "use_config_min_sale_qty": 1,
            "min_sale_qty": 1,
            "use_config_max_sale_qty": true,
            "max_sale_qty": 10000,
            "use_config_backorders": true,
            "backorders": 0,
            "use_config_notify_stock_qty": true,
            "notify_stock_qty": 1,
            "use_config_qty_increments": true,
            "qty_increments": 0,
            "use_config_enable_qty_inc": true,
            "enable_qty_increments": false,
            "use_config_manage_stock": true,
            "manage_stock": true,
            "low_stock_date": null,
            "is_decimal_divided": false,
            "stock_status_changed_auto": 0
        }
    },
    "options": [],
    "media_gallery_entries": [],
    "custom_attributes": [
        {
            "attribute_code": "options_container",
            "value": "container2"
        },
        {
            "attribute_code": "msrp_display_actual_price_type",
            "value": "0"
        },
        {
            "attribute_code": "url_key",
            "value": "vintage-backpack"
        },
        {
            "attribute_code": "required_options",
            "value": "0"
        },
        {
            "attribute_code": "has_options",
            "value": "0"
        },
        {
            "attribute_code": "tax_class_id",
            "value": "2"
        },
        {
            "attribute_code": "category_ids",
            "value": [
                "11",
                "12",
                "16"
            ]
        },
        {
            "attribute_code": "description",
            "value": "Vintage Backpack is a heavyweight washed cotton canvas backpack with a large main compartment, a front pocket, and two side pockets."
        },
        {
            "attribute_code": "size",
            "value": "20"
        },
        {
            "attribute_code": "color",
            "value": "42"
        }
    ]
}

magento-rest-api-product

Verify the Results

Go to the Admin Panel and navigate to the Catalog → Products. You will see the newly created product in the product grid. If no results, search with the product name.

magento-rest-api-verify-product

Create Custom REST API Module

Although Magento 2 provides numerous REST endpoints, check out the list of Endpoints by Module for managing and controlling the custom data for your application; these REST APIs may not be a good fit. Therefore, you must create the custom Magento REST API with data and values. I will explain all the necessary information in simple steps.

Step 1: Create Rest API Custom Module

We will create Cloudways_RestApi as the namespace for this tutorial. Create module.xml and registration.php files in the following structure.

app/code/Cloudways/RestApi/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="Cloudways_RestApi" setup_version="1.0.0" />
</config>

app/code/Cloudways/RestApi/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(

    \Magento\Framework\Component\ComponentRegistrar::MODULE,

    'Cloudways_RestApi',

    __DIR__

);

Step 2: Define Custom Endpoint

To define custom endpoints, we need to configure a web API service, create webapi.xml as described in app/code/Cloudways/RestApi/etc/webapi.xml

<?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/rest_dev/custom-api/">
        <service class="Cloudways\RestApi\Api\CustomInterface" method="getData" />
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Step 3: Configure the Dependency

The di.xml file loads the dependencies injected with the Object Manager and creates the di.xml described in app/code/Cloudways/RestApi/etc/di.xml to configure the interface.

<?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="Cloudways\RestApi\Api\CustomInterface" type="Cloudways\RestApi\Model\Api\Custom"/>

</config>

Step 4: Create Interface

For this Magento 2 Rest API, I created the interface for the request in app/code/Cloudways/RestApi/Api/CustomInterface.php

<?php

namespace Cloudways\RestApi\Api; 

interface CustomInterface

{

    /**

     * GET for Post api

     * @param string $value

     * @return string

     */

 

    public function getData($value);

}

Step 5: Create a Model

Models are the classes that implement the interface’s functionality and process the data. In the Magento 2 REST API, I create the model to implement the interface function getData to respond and provide the requested data for the given request.

<?php 

namespace Cloudways\RestApi\Model\Api; 

use Psr\Log\LoggerInterface;

class Custom

{

    protected $logger;

    public function __construct(

        LoggerInterface $logger

    )

    {

        $this->logger = $logger;

    }

 

    /**

     * @inheritdoc

     */

    public function getData($value)

    {

        $response = ['success' => false];

        try {

            // Implement 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 6: Test your Custom Magento 2 Rest API

Finally, run the upgrade command using CLI, then test your Magento 2 REST API call. In this example, we will test the endpoint with Postman.

Request

GET Endpoint

http://magento-761105-2575467.cloudwaysapps.com/index.php/rest/V1/rest_dev/custom-api

Response

{

  "success":true,

  "message":"This is test string provided"

}

Payload

{

"value": "This is the test string provided"

}

magento-custom-api-module

Summary

This extensive topic requires a series of tutorials for complete coverage. The goal of this tutorial was to provide a simple example and demonstrate how easy it is to use Magento 2 REST API. I hope you found this tutorial useful. Feel free to get in touch if you need any help with the topic. I would love to answer your question.

Frequently Asked Questions

Q. How to create a web service role in Magento 2?

A. To create a web service role in Magento 2, follow these steps:

  1. Log in to the Magento 2 Admin Panel.
  2. Go to SystemUser Roles and tap the Add New Role
  3. Enter the Role Name.
  4. In Your Password field, enter the current password of your Magento 2 Admin.
  5. Now, on the left side, click Role Resources.
  6. In the Resource Access, select only those that are required for your web service.
  7. Once done, hit the Save Role

Q. How to Create Web Service User in Magento 2?

A. Now, create a new user for the newly created role through these steps:

  1. Go to SystemAll Users and hit the Add New User
  2. Enter the required information, including User Name, First and Last Name, Email, Password, etc.
  3. Now, on the left side, click User Role and select the newly created role.
  4. Once done, click the Save User
Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Great speed, features, knowledgebase, dashboard, UX and fast, expert support. Very happy!”

Stefan [Management Consultant]

Jyotishna Kumari

Jyotishina is the Magento Community Expert at Cloudways and has 4 years of experience in web development. She has worked on e-commerce sites since the turn of the millennium and was working with Magento before version 1 was released. She loves to travel and explore new ideas whenever she finds time. Get in touch with her at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Unleash The Cloud.
Not Budgets.

For 4 Months +
Up To 30 Free Migrations

Cyber Week

SAVINGS
Time Left In Offer
  • 0

    Days

  • 0

    Hours

  • 0

    Minutes

  • 0

    Seconds

40% OFF

On All Plans

GET THE DEAL NOW