Getting Started with Magento Web APIs (REST & SOAP)

0
16849
Getting Started with Magento Web APIs | Mageworx Magento Blog
Reading Time: 4 minutes

The Magento 2 Web API framework offers users an opportunity to create new services that can communicate with third-party modules. They are Magento 2 supports REST and SOAP web services based on CRUD operations (create, read, update, and delete).

In this article, we will explain the initial steps of using Magento 2 API. These APIs speed up the processing power and facilitate the transmission of data, such as products, customers, or orders, as well as transferring it to a third-party system. It also helps you manage the inventory. 

By automating the process, the usage of API helps you write less code.

Table of Contents

What are Magento Web APIs?

The Magento web API is very easy to understand for developers looking to use web services that help communicate with the Magento system. These features are key to the API:

  • Magento 2 supports both REST (Representational State Transfer) and SOAP (Simple Object Access Protocol). 
  • It offers three types of authentication: 1) OAuth 1.0a for third-party application authentication, 2) the tokenization method for mobile application authentication, and 3) login credential for administration and customer verification.
  • You can configure any Magento or third-party web API by writing a few lines of XML.
  • It supports field filtering of web API that conserve the mobile response. 
  • The current framework is based on the CRUD (create, read, update, delete) and search model.

What Can You Do With the Magento Web APIs?

APIs help various modules communicate with each other. They can be used to perform a wide array of tasks. For example:

  • You can create online stores using Magento, and connect them with a physical system like POS (Point of Sale) to control the inventory globally 
  • Easily integrate with CRM (Customer Relationship Management) or ERP (Enterprise Resource Planning) backend systems such as Salesforce, Microsoft Dynamics, or other sound software
  • It helps to connect with the CMS (Content Management System)
  • You can also create JavaScript widgets on the Magento backend (Admin panel) or Magento storefront

Getting Started: With Magento 2 Rest API

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

1.Log in to the Magento 2 Admin Panel.

2.Go to System >> User Roles and click the Add New Rolebutton.

Getting Started with Magento Web APIs | Mageworx Magento Blog

3. Enter the Role name.

Getting Started with Magento Web APIs | Mageworx Magento Blog

4. In the Your Password field, enter the current password of your Magento 2 Admin.

Getting Started with Magento Web APIs | Mageworx Magento Blog

5.On the left-hand side, click Role Resources. Under Resource Access, select only what is required for your web service.

Getting Started with Magento Web APIs | Mageworx Magento Blog

6.Once done, hit the Save Role.

Create Web Service User in Magento 2

Create a new user for the newly created role by following these steps:

1.Go to System >> All Users, and then click Add New User.

Getting Started with Magento Web APIs | Mageworx Magento Blog

2.Enter the required information, including User Name, First and Last Name, Email, and Password.

Getting Started with Magento Web APIs | Mageworx Magento Blog

3. On the left-hand side, click User Role, and then select the newly created role. Once done, click the Save Userbutton.

Getting Started with Magento Web APIs | Mageworx Magento Blog

Magento 2 REST API Authentication

Here, I will authenticate REST API through the token authentication method. This involves passing a username and password in the initial connection and receiving a token that will be saved in a variable for further calls.

<?php
//API URL for authentication
$apiURL="http://magento-91647-257956.cloudwaysapps.com/index.php/rest/V1/integration/admin/token";
//parameters passing with URL
$data = array("username" => "username", "password" => "********");
$data_string = json_encode($data);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Content-Length: ".strlen($data_string)));
$token = curl_exec($ch);
//decoding generated token and saving it in a variable
$token=  json_decode($token); 
?>

Please note: The username & password are used as an example.

Get Modules Using REST API in Magento 2

You can fetch data using the Magento 2 REST API. Here’s a complete list of REST APIs for Magento EE and CE. 

<?php
//Using above token into header
$headers = array("Authorization: Bearer ".$token);
//API URL to get all Magento 2 modules
$requestUrl='YourgeneratedUrl';
$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
//decoding result
$result=  json_decode($result);
//printing result
print_r($result);
?>

In the above code, I already passed the token (which was fetched earlier) with the API URL to get all the modules installed on the Magento 2 store.

Here’s the complete code.

<?php
//API URL for authentication
$apiURL="URL";
//parameters passing with URL
$data = array("username" => "username", "password" => "*********");
$data_string = json_encode($data);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Content-Length: ".strlen($data_string)));
$token = curl_exec($ch);
//decoding generated token and saving it in a variable
$token=  json_decode($token);
//******************************************//
//Using above token into header
$headers = array("Authorization: Bearer ".$token);
//API URL to get all Magento 2 modules
$requestUrl='YourURL';
$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
//decoding result
$result=  json_decode($result);
//printing result
print_r($result);
?>

Use SOAP Services

Before we get into the SOAP services, it’s important to learn about Magento’s naming conventions:

  • You have to use the CamelCase for naming services. For example, MyFirstModule
  • The string “Service” is omitted, meaning you can’t use it.
  • The “Magento” prefix and the “Interface” suffix are also escalated.
  • If your ‘service’ name is the same as the ‘module’ name, the module name will be omitted.

MageWorx Updates Roundup | MageWorx Blog

So, make sure to keep these points in mind.

SOAP Services―Authentication Using Magento 2

SOAP resources can be accessed using OAuth access tokens over HTTP. OAuth authentication is similar to the token method but supplies a more complex arrangement. Access tokens are strings that represent an access authorization issued to the client. 

Here is the PHP script that explains how to get an access token:

<?php
$opts = [
            'http'=> [
                'header' => 'Authorization: Bearer 36849300bca4fbff758d93a3379f1b8e'
            ]
        ];
$wsdlUrl = 'http://magento.ll/soap/default?wsdl=1&services=testModule1AllSoapAndRestV1';
$serviceArgs = ["id" => 1];

$context = stream_context_create($opts);
$soapClient = new SoapClient($wsdlUrl, ['version' => SOAP_1_2, 'stream_context' => $context]);

$soapResponse = $soapClient->testModule1AllSoapAndRestV1Item($serviceArgs); ?>

Final Words

This article outlined the basics of Magento web APIs, but there’s a lot more you could learn. If you want a firmer grasp on the Magento 2 API usage, then you should explore how methods are built-in Magento 2 and third-party extensions. You should also understand how to pass the information to the needed system.

So, that’s it!

To experience faster Magento hosting with peace of mind, check out this 3-day free trial on DigitalOcean, Vultr, and Linode.

LEAVE A REPLY

Please enter your comment!
Please enter your name here