HowTo: Create a REST API Call in Magento 2

These code snippets will show you how to ask the Magento REST API and retrieve some data.
In this example I will query the Magento REST API to retrieve all products updated since 2018-10-09 00:00:00.

This method assumes:

  • You are using an admin user to generate the token.
  • You have a Magento2 instance running in your local environment.

Getting the Authentication Token

Create a php file with the following:

<?php
// API URL for authentication
$apiURL = "https://magento2.test/index.php/rest/V1/integration/admin/token";

// Parameters passing with URL
$data = ["username" => "admin", "password" => "magento123"];
$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, ["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);

echo 'Token is:' . $token . PHP_EOL;

Then execute that file from your terminal.

$ php magento_api_test.php

This will connect to your Magento instance using the credentials of an admin user to generate a token that you will use later to interact with the REST API.

The output of the previous command should be similar to this:

$ Token is: xjggqmqgb7cdxcvy9svoo0dr0pee6ijg

Using the Generated Token

Remove the echo line and add the following to your php file:

// Using above token into header
$headers = ["Authorization: Bearer " . $token];

// API URL to get all products with updated_at greater than a date
// /rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=updated_at&searchCriteria[filter_groups][0][filters][0][value]=2018-10-09%2000:00:00&searchCriteria[filter_groups][0][filters][0][condition_type]=gt&searchCriteria[pageSize]=1
$requestUrl = "https://magento2.test/rest/V1/" .
    "products?" .
    "searchCriteria[filter_groups][0][filters][0][field]=updated_at&" .
    "searchCriteria[filter_groups][0][filters][0][value]=2018-10-09%2000:00:00&" .
    "searchCriteria[filter_groups][0][filters][0][condition_type]=gt&" .
    "searchCriteria[pageSize]‌=10&";

$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
var_dump($result);

Related links:

Comments

Next Post Previous Post