Understanding Magento REST API: Simplified 101

By: Published: October 13, 2021

Magento REST API - Featured Image

Magento (Adobe Commerce) is one of the widely used E-Commerce platforms by more than 250,000 merchants worldwide. To manage your workflows and orders, prices, stocks, etc., one needs the help of 3rd party tools and platforms. Magento REST APIs allow developers to integrate Magento (Adobe Commerce) with other applications easily. If you are a developer and want to add more features to your application with Magento then you should use the Magento REST APIs.

Magento (Adobe Commerce) also provides documentation for using its REST APIs. The Magento REST APIs are the fast, efficient, and reliable way to integrate any app with Magento (Adobe Commerce). Software providers require Magento REST APIs for shipping management, order and inventory management, Marketing Automation, CRM, and ERP solutions.

Magento REST APIs Integration allows apps to access data from Magento stores to other apps and platforms. In this article, you will learn about Magento REST APIs, how to work with REST APIs using cURL. You will also read about the elements of the Magento REST APIs.

Table of Contents

What is Magento (Adobe Commerce)?

Magento (Adobe Commerce Cloud) Logo
Image Source

Magento (Adobe Commerce) is an E-Commerce platform entirely built on PHP frameworks. It allows developers to quickly set up an E-Commerce website using its pre-built components essential for the basic functioning of any E-Commerce website. Magento (Adobe Commerce) is an open-source platform, and anyone can access its source code and customize it according to their needs. 

Magento (Adobe Commerce) is available in 2 versions or packages, i.e. Magento Open-Source and Magento Commerce, where both the packages contain a basic version of the Magneto site. Magento Open-Source is free to use, and the Magento Commerce version is paid and comes with additional advanced features to provide greater flexibility. It offers many themes, widgets, apps, extensions, and much more to help users start an online store quickly.

Key Features of Magento (Adobe Commerce)

Magento (Adobe Commerce) allows retail sellers to effortlessly set up an enterprise-level E-Commerce website. Many features attract people for using it. A few of them are listed below:

  • Multi-Platform Integrations: Magento (Adobe Commerce) supports integrations with many apps, platforms, and services used in the industry to optimize and manage the workflow. 
  • SEO optimized: Magento (Adobe Commerce) takes your reach to customers and visibility on search engines. It is designed to render SEO (Search Engine Optimization) optimized content on your site, which will help you rank higher on search engines.
  • Customizable Themes: It comes with a theme store that contains a collection of themes for every category and business. The themes fasten the process of building an E-Commerce website.

To learn more about Magento (Adobe Commerce), click here.

Introduction to REST APIs

REST API Cover Image
Image Source

REST API stands for Representational State Transfer Application Programming Interface is a software architecture style used to guide the design and development of the architecture for the World Wide Web. It defines some set of constraints on how the architecture of internet-scaled distributed systems should work. In a typical 3-tier application, it stands between the User Interface (which allows end-users to access and alter data), and the Database (which stores the data). 

Magento REST API - API Dataflow
Image Source

An HTTP request is used to access and use the data with commands such as PUT, GET, DELETE, POST, etc. The components are loosely coupled which makes the data flow through HTTP fast and efficient. REST APIs are easier to create and manage because the data formats are not pre-defined and can be used for wider purposes.

To learn more about REST APIs, click here.

Simplify Data Analysis with Hevo’s No-code Data Pipeline

Hevo Data, a No-code Data Pipeline helps to load data from any data source such as Databases, SaaS applications, Cloud Storage, SDKs, external connectors for REST API, and Streaming Services and simplifies the ETL process. It supports 100+ data sources including external connectors for Magento REST APIs and is a 3-step process by just selecting the data source, providing valid credentials, and choosing the destination. Hevo not only loads the data onto the desired Data Warehouse/destination but also enriches the data and transforms it into an analysis-ready form without having to write a single line of code.

Get Started with Hevo for Free

Its completely automated pipeline offers data to be delivered in real-time without any loss from source to destination. Its fault-tolerant and scalable architecture ensures that the data is handled in a secure, consistent manner with zero data loss and supports different forms of data. The solutions provided are consistent and work with different BI tools as well.

Check out why Hevo is the Best:

  1. Secure: Hevo has a fault-tolerant architecture that ensures that the data is handled in a secure, consistent manner with zero data loss.
  2. Schema Management: Hevo takes away the tedious task of schema management & automatically detects the schema of incoming data and maps it to the destination schema.
  3. Minimal Learning: Hevo, with its simple and interactive UI, is extremely simple for new customers to work on and perform operations.
  4. Hevo Is Built To Scale: As the number of sources and the volume of your data grows, Hevo scales horizontally, handling millions of records per minute with very little latency.
  5. Incremental Data Load: Hevo allows the transfer of data that has been modified in real-time. This ensures efficient utilization of bandwidth on both ends.
  6. Live Support: The Hevo team is available round the clock to extend exceptional support to its customers through chat, E-Mail, and support calls.
  7. Live Monitoring: Hevo allows you to monitor the data flow and check where your data is at a particular point in time.
Sign up here for a 14-Day Free Trial!

Elements of a Magento REST APIs

Magento REST API Cover Image
Image Source

The Magento REST APIs contain many functions that are used to send requests and receive a response. All the interactions or tasks of receiving and sending data are performed using the HTTP protocol. Magento REST APIs includes the elements listed below:

HTTP Headers

There are 3 HTTP headers in Magento REST APIs listed in the table below:

HTTP HEADERDESCRIPTIONSYNTAX
AuthorizationIt is a required field, except for calls made on behalf of a guest. This Magento REST APIs header specifies the authentication token for the Magento (Adobe Commerce) account. You specify the token in the Authorization request header with the Bearer HTTP authorization scheme.Authorization: Bearer <TOKEN>
<TOKEN> is the authentication token returned by the Magento (Adobe Commerce) token service. 
AcceptIt is an optional field that specifies the format of the response body. The default format is JSON.Accept: application/<FORMAT>
<FORMAT> is either JSON or XML.
Content-TypeIt is a required field for operations with a request body that is used to specify the format of the request body.Content-Type:application/<FORMAT>
<FORMAT> is either JSON or XML.

HTTP Verb

A Magento REST APIs has 4 HTTP verbs, and each has a different role. Users can call any of the following HTTP verbs in the requests. The HTTP verbs for Magento REST APIs are listed below:

  • GET: GET is the default HTTP verb, and it requests the transfer of the current state of the target resource.
  • PUT: It contains a message payload in the request and creates or replaces the state of the target resource with the state defined in the message payload.
  • POST: It requests that the server accept the message enclosed in the request as data to be processed by the target.
  • DELETE: It requests that the origin server delete the target resource.

Endpoint

An endpoint is a combination of the server that can perform actions on a request, the store code, the web service against the request, and any template parameters.

For example in the endpoint “http://magento.ll/index.php/rest/default/V1/customerGroups/:id”, the server is “magento.ll/index.php/”, the web service part is rest, the resource is “/V1/customerGroups” and the template parameter is “id”. The store code is by default is null and the value “all” only applies in the endpoints in the Product Modeles and CMS. The value affects all the merchant stores.

Call Payload

The Magento REST APIs have both required and optional inputs. The call payload is a set of parameters that one can ad with the request and send to the target resource.

A URI (Uniform Resource Identifier ) is present in the Request message header. You can input parameters in URI like “GET/V1/customers/:customerId”, where the “customerId” is the template parameter that will filter out the response by the specified customer ID.

You can provide the input attributes in JSON or XML format. An example code for the request body is shown below:

{
    "customer": {
        "email": "user@example.com",
        "firstname": "John",
        "lastname": "Doe"
    },
    "addresses": [
        {
            "defaultShipping": true,
            "defaultBilling": true,
            "firstname": "John",
            "lastname": "Doe",
            "region": {
                "regionCode": "CA",
                "region": "California",
                "regionId": 12
            },
            "postcode": "90001",
            "street": ["Zoe Ave"],
            "city": "Los Angeles",
            "telephone": "555-000-00-00",
            "countryId": "US"
        }
    ]
}

Steps to Run Magento REST APIs Via cURL

Now that you have understood Magento REST APIs and its basic structure and elements. In this section, you will learn the steps to run the requests using cURL. A cURL is a command-line tool that allows users to send HTTP requests and receive responses. The steps for using cURL requests in Magento REST APIs are listed below:

Calling a Magento REST APIs Request

You will now learn the steps to create an account using Magento REST APIs. The steps are listed below: 

  • Open the file “Magento/Customer/etc/webapi.xml” by clicking here.
  • Now, search for the route element that defines the “createAccount” call, as shown in the code below:
<route url="/V1/customers" method="POST">
   <service class="MagentoCustomerApiAccountManagementInterface" method="createAccount"/>
   <resources>
      <resource ref="anonymous"/>
   </resources>
</route>
  • Now, construct the URI by using the values of “method” and “url” in the route element. For the above code, the URI will be POST /V1/customers.
  • Next, use the class attribute in the service element for identifying the service interface. For this example, the service interface is the “AccountManagementInterface.php” file. Get the PHP file here. Open the file and search for the “createAccount” method as shown in the code below.
public function createAccount(
     MagentoCustomerApiDataCustomerInterface $customer,
     $password = null,
     $redirectUrl = ''
 )
  • The “customer” data object is required to call “createAccount”. For passing the “customer” data request in the POST call payload, specify JSON or XML request body on the call.
  • Magento (Adobe Commerce) offers its service wrapper to use cURL instead of using PHP cURL. To create an instance of the class MagentoFrameworkHTTPClientCurl. The code for reference is shown below:
/**
* Constructor.
*
* @param MagentoFrameworkHTTPClientCurl $curl
*/
public function __construct(
   MagentoFrameworkHTTPClientCurl $curl
) {
   $this->curl = $curl;
}

Magento REST APIs: GET Request

The GET request allows users to request a target resource. The code for making a GET request with Magento REST APIs using cURL is shown below:

// get method
$this->curl->get($url);

// output of curl request
$result = $this->curl->getBody();

Here, “$url” is the endpoint URL.

Magento REST APIs: POST Request

The POST request in Magento REST APIs allows users to send data in enclosed payload messages. The example code is shown below:

// post method
$this->curl->post($url, $params);

// output of curl requestt
$result = $this->curl->getBody();

Here “$url” is the endpoint URL. the “$params” attribute is an array of data to be sent using a POST request. An example of “$params” is shown below.

$params = [
  'user[email]' => $user->getEmail(),
  'user[cellphone]' => $providerInfo['phone_number'],
  'user[country_code]' => $providerInfo['country_code'],
]

Conclusion

In this article, you learnt about the Magento REST APIs and the steps to implement the basic commands using cURL. You also read about the elements of Magento REST APIs. Magento REST APIs allow developers to integrate Magento (Adobe Commerce) with other platforms and tools to optimize the workflow and developing new applications. Magento (Adobe Commerce) is a versatile E-Commerce platform that offers all the features for enterprises.

Visit our Website to Explore Hevo

Companies need E-Commerce data to analyze it and generate insights from it. The manual process of extracting data from Magento (Adobe Commerce) is tedious. Hevo Data is a No-code Data Pipeline that can help you transfer data from Magento (Adobe Commerce) to desired Data Warehouse. It fully automates the process to load and transform data from 100+ sources to a destination of your choice without writing a single line of code. 

Want to take Hevo for a spin? Sign Up here for a 14-day free trial and experience the feature-rich Hevo suite first hand.

Share your experience of learning about Magento REST APIs in the comments section below!

mm
Former Research Analyst, Hevo Data

Aditya has a keen interest in data science and is passionate about data, software architecture, and writing technical content. He has experience writing around 100 articles on data science.

No-code Data Pipeline For your Data Warehouse