The Totally Beginners Guide to Magento 2 REST API
Magento is a very popular, open source eCommerce tool. Magento 2 (like Magento 1) provides a REST API that you can use to create powerful applications harnessing the power of Magento. This guide will help you get up and running in a short amount of time in integrating the Magento 2 REST API in your application. The official documentation may feel insufficient to most beginners so in this article, I will be providing specific examples in PHP.
Magento supports REST and SOAP APIs although REST API will be better suited to beginners hence we will be implementing the REST API.
First, we must register a web service on Magento. Following are the steps listed in the official documentation:
1. Create a web services user on Magento Admin by selecting System > All Users > Add New User.
This step is required for token-based authentication. Since we will be performing this type of authentication, the first step needs to be done.
2. Create a new integration on Magento Admin. To create an integration, click System > Integration > Add New Integration. Be sure to restrict which resources the integration can access.
Authentication
Before we start performing requests, we need some type of authentication to access our Magento Store. Magento provides three methods of authentication:
Token Based, Session Based or OAuth-based. Following is an example of token based authentication in PHP:
$userData = array("username" => "admin-username", "password" => "admin-password");
$ch = curl_init("http://YOUR_MAGENTO_HOST/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Length: " . strlen(json_encode($userData))));
$token = curl_exec($ch);
We establish the initial connection using the admin username and password and get the token. This token can then be used for requests until the token expires (by default, its valid for 4 hrs in case of admin and this duration can be changed).
Request Methods
There are three request methods: GET, POST and PUT which can be utilized according to the application requirements. The list of REST endpoints can be found here.
- GET
Example
$request = "http://YOUR-MAGENTO-HOST/rest/V1/products/24-BB"; $ch = curl_init($request);curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
$result = curl_exec($ch);
var_dump($result);
In the above snippet, 24-BB is the sku (unique product identifier) of a sample product. This request returns the detail of the product in json form:
string(1407) "{"id":2047,"sku":"24-BB","name":"New Bag","attribute_set_id":15,"price":43,"status":1,"visibility":4,"type_id":"simple","created_at":"2018-01-09 08:48:46","updated_at":"2018-01-09 15:47:28","weight":5,"extension_attributes":{"website_ids":[1],"stock_item":{"item_id":2047,"product_id":2047,"stock_id":1,"qty":10,"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":0,"min_sale_qty":0,"use_config_max_sale_qty":true,"max_sale_qty":10000,"use_config_backorders":false,"backorders":0,"use_config_notify_stock_qty":true,"notify_stock_qty":1,"use_config_qty_increments":false,"qty_increments":0,"use_config_enable_qty_inc":false,"enable_qty_increments":false,"use_config_manage_stock":true,"manage_stock":true,"low_stock_date":null,"is_decimal_divided":true,"stock_status_changed_auto":0}},"product_links":[],"options":[],"media_gallery_entries":[],"tier_prices":[],"custom_attributes":[{"attribute_code":"description","value":"m"},{"attribute_code":"short_description","value":"n"},{"attribute_code":"color","value":"49"},{"attribute_code":"category_ids","value":[]},{"attribute_code":"options_container","value":"container2"},{"attribute_code":"required_options","value":"0"},{"attribute_code":"has_options","value":"0"},{"attribute_code":"url_key","value":"new-bag"},{"attribute_code":"tax_class_id","value":"2"}]}"
Indeed, this is a lot of detail. To get only a few attributes, you can retrieve filtered responses by modifying the request as in the example below:
$request = "http://YOUR-MAGENTO-HOST/rest/V1/products/24-BB?fields=id,name,price";
This request returns only three attributes: id, name and price.
Magento also provides the option of search through REST API. For example, if we want to retrieve the invoices created after a specified date, we could use the following request:
$request = "http://YOUR-MAGENTO-HOST/rest/V1/invoices?searchCriteria[filter_groups][0][filters][0][field]=created_at&searchCriteria[filter_groups][0][filters][0][value]=2018-01-08 00:00:00&searchCriteria[filter_groups][0][filters][0][condition_type]=gt";
This retrieves the invoices created after (specified by gt) 2018–01–08 00:00:00.
2. POST
Example:
$curl = curl_init();
$post ='{
"product": {
"sku": "24-BV",
"name": "Sample",
"price": 20,
"status": 1,
"visibility": 4,
}
}';curl_setopt_array($curl, array(
CURLOPT_URL => "http://YOUR-MAGENTO-HOST/rest/V1/products",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $post,
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"content-type: application/json",
"authorization: Bearer " . json_decode($token),
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
The above code creates a new product in the Magento store with the attributes that have been specified.
3. PUT
Example: To edit the attributes of any product, we could use a PUT request. This time we would have to specify the sku of the existing product in the url:
$curl = curl_init();
$post ='{
"product": {
"sku": "24-BV",
"name": "New Name",
"price": 30,
"status": 1,
"visibility": 4,
}
}';curl_setopt_array($curl, array(
CURLOPT_URL=>"http://YOUR-MAGENTO-HOST/rest/V1/products/24-BV",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => $post,
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"content-type: application/json",
"authorization: Bearer " . json_decode($token),
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
In this article I demonstrated three fairly basic examples on the usage of Magento 2 REST API. These should be sufficient to get started and for more info, the official documentation is below:
Feel free to ask any any question in the comments regarding the Magento 2 REST API!