Magento 2 API usage with examples

Magento 2 API

Magento 2 supports REST (Representational State Transfer) and SOAP (Simple Object Access Protocol), much like the old version of Magento we were used to. Official documentation is mostly based on raw curl request without examples in some specific language. PHP is what we do and there will be many people using it as well, so we tried to give you real PHP examples of how to connect and use Magento 2 API.

There are three user types that have access to API in Magento and those are:

1) Guest user
They have access to resources with anonymous permission.

2) Administrator/Integration
They have access to resources for which are authorized by configuration.

3) Customer
They have access to resources with self or anonymus permission.

There are three types of authentication that we can use:

1) Token-based authentication

Idea here is to provide username and password during initial connection and receive the token to be used for requests that follow, until token expires.

Here is example using rest API via PHP

<?php
$userData = array("username" => "inchoo", "password" => "mypassword");
$ch = curl_init("http://magento.m2/index.php/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CUsRLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));
 
$token = curl_exec($ch);
 
$ch = curl_init("http://magento.m2/index.php/rest/V1/customers/1");
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);

If we run this code, we will get a response that looks like something like this:

string(338) "{"id":1,"group_id":1,"default_billing":"0","default_shipping":"0","created_at":"2016-08-16 08:37:59","updated_at":"2016-08-16 08:38:00","created_in":"Default Store View","email":"tomas.novoselic@gmail.com","firstname":"Tomas","lastname":"Novoseli\u0107","gender":1,"store_id":1,"website_id":1,"addresses":[],"disable_auto_group_change":0}"

There is another example using SOAP API via PHP

<?php
$request = new SoapClient("http://magento.m2/index.php/soap/?wsdl&services=integrationAdminTokenServiceV1", array("soap_version" => SOAP_1_2));
$token = $request->integrationAdminTokenServiceV1CreateAdminAccessToken(array("username"=>"inchoo", "password"=>"GN2vKgfsszz43u"));
 
$opts = array(
            'http'=>array(
                'header' => 'Authorization: Bearer '.json_decode($token->result)
            )
        );
 
$wsdlUrl = 'http://magento.m2/soap/default?wsdl&services=directoryCurrencyInformationAcquirerV1';
 
$context = stream_context_create($opts);
$soapClient = new SoapClient($wsdlUrl, ['version' => SOAP_1_2, 'context' => $context]);
 
$soapResponse = $soapClient->__getFunctions();

which gives us the following response:

<?php
array(1) {
  [0]=>
  string(196) "DirectoryCurrencyInformationAcquirerV1GetCurrencyInfoResponse directoryCurrencyInformationAcquirerV1GetCurrencyInfo(DirectoryCurrencyInformationAcquirerV1GetCurrencyInfoRequest $messageParameters)"
}

2) Session-based authentication

Session based authentication seems to be most simple of all three.
In short, Magento API framework uses your session in order to authorize access to the requested resource.
For example, create frontend user, log in and point your browser to this page: http://magento.m2/rest/V1/customers/me

You will get something like this as result:

<response>
<id>2</id>
<group_id>1</group_id>
<created_at>2016-08-17 08:48:00</created_at>
<updated_at>2016-08-17 09:32:42</updated_at>
<created_in>Default Store View</created_in>
<email>tomas@inchoo.net</email>
<firstname>Tomas</firstname>
<lastname>Novoselic</lastname>
<store_id>1</store_id>
<website_id>1</website_id>
<addresses/>
<disable_auto_group_change>0</disable_auto_group_change>
</response>

As a customer, you will be authorized to access resources with self and anonymous permission. However, it also works for admin accounts if you try to access resource for which your admin account has permission .

3) OAuth-based authentication

Access to API is allowed via OAuth 1.0a (https://en.wikipedia.org/wiki/OAuth).
In this case, think of Magento API as a service that allows access to resources to third party via approval gotten from resource owners.
For example, getting customer (resource owner) info from Magento API (service) from third party application (client).
This is little bit out of the scope for this article and separate article is in preparation, however there is simple example of using integration without “Identity link URL” and “Callback URL”.

What you need to do is to go to System > Integrations and add new integration without “Identity link URL” and “Callback URL”. Remember to edit resource access on API tab.

Then run this script:

<?php
function sign($method, $url, $data, $consumerSecret, $tokenSecret)
{
	$url = urlEncodeAsZend($url);
 
	$data = urlEncodeAsZend(http_build_query($data, '', '&'));
	$data = implode('&', [$method, $url, $data]);
 
	$secret = implode('&', [$consumerSecret, $tokenSecret]);
 
	return base64_encode(hash_hmac('sha1', $data, $secret, true));
}
 
function urlEncodeAsZend($value)
{
	$encoded = rawurlencode($value);
	$encoded = str_replace('%7E', '~', $encoded);
	return $encoded;
}
 
// REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION
$consumerKey = '1fuj3asjsk4w3qb3cx44ik5ue188s30s';
$consumerSecret = 'lcey0h5uyt26slvtws5okaiqh8ojju5d';
$accessToken = 'b41sqrw1cfqh598yfoygd836c4ll3cr8';
$accessTokenSecret = 'lywj45gighqo3knl6bv6i61n2jf6iv0a';
 
$method = 'GET';
$url = 'http://magento.m2/index.php/rest/V1/customers/2';
 
//
$data = [
	'oauth_consumer_key' => $consumerKey,
	'oauth_nonce' => md5(uniqid(rand(), true)),
	'oauth_signature_method' => 'HMAC-SHA1',
	'oauth_timestamp' => time(),
	'oauth_token' => $accessToken,
	'oauth_version' => '1.0',
];
 
$data['oauth_signature'] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret);
 
$curl = curl_init();
 
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $url,
	CURLOPT_HTTPHEADER => [
		'Authorization: OAuth ' . http_build_query($data, '', ',')
	]
]);
 
$result = curl_exec($curl);
curl_close($curl);
var_dump($result);

and expect something like this for response:

string(268) "{"id":2,"group_id":1,"created_at":"2016-08-17 08:48:00","updated_at":"2016-08-17 09:32:42","created_in":"Default Store View","email":"tomas@inchoo.net","firstname":"Tomas","lastname":"Novoselic","store_id":1,"website_id":1,"addresses":[],"disable_auto_group_change":0}"

Conclusion:

Unfortunately, topic is kind of big to effectively tackle in one blog article. More detailed OAuth-based authentication and creation of your own custom API is coming soon in another blog post.
I hope this one has useful examples that can get you started and that we can add more details in the future when we all get more familiar with Magetno 2 API.
Until then, we can find more info in the official documentation: http://devdocs.magento.com/guides/v2.0/get-started/bk-get-started-api.html


About Tomas Novoselic

Team Leader/Backend Developer

At Inchoo, Tomas is a Team Leader and Certified Magento Developer who handles Magento modifications at any level. He also works closely with clients on Magento projects of any size and difficulty.

Read more posts by Tomas / Visit Tomas's profile

11 comments

  1. I have created custom module now i want to call method using soap.

    
    $request = new SoapClient("http://localhost:8080/magento2/index.php/soap/?wsdl&services=integrationAdminTokenServiceV1", array("soap_version" => SOAP_1_2));
    $token = $request->integrationAdminTokenServiceV1CreateAdminAccessToken(array("username"=>"test", "password"=>"test123"));
     
    $opts = array(
                'http'=>array(
                    'header' => 'Authorization: Bearer '.json_decode($token->result)
                )
            );
     
    $wsdlUrl = 'http://localhost:8080/magento2/soap/default?wsdl&services=training5VendorRepositoryV1';
     
    $context = stream_context_create($opts);
    $soapClient = new SoapClient($wsdlUrl, ['version' => SOAP_1_2, 'context' => $context]);
     
    $soapResponse = $soapClient->__getFunctions();
    
    print_r($soapResponse);
    

    I am getting below output:
    Array ( [0] => Training5VendorRepositoryV1GetListResponse training5VendorRepositoryV1GetList(Training5VendorRepositoryV1GetListRequest $messageParameters) )

    But how can i call training5VendorRepositoryV1GetList method and get data from this method.

    using rest i am getting data properly can you please suggest me how can i get data using soap. Thanks!

  2. Hi, I’m getting crazy using query string with search criteria. (“searchCriteria[filter_groups][0][filters][0][field]”…).
    I obtain always the error “Invalid signature”. Could you make an example with a GET request and a query string?

    1. Hi.
      I also have the same problems. Getting “Invalid signature” response when having GET parameters in the URL.
      Don’t know where the problem lies exactly ….

      Ludo

  3. Hi,

    Could you please answer some qustions regarding APIS?

    I am an API Consumer looking to build a an application layer on top of Magento REST APIs. I have a basic question and I hope you don’t mind answering it.

    I wasn’t able to find any documentation that points to difference in APIs across all 3 editions of Magento i.e. Community, Enterprise and Enterprise cloud. Can you confirm that REST APIs are same across all 3 of them or point me to relevant docs that outlines the differences.

  4. I’m really looking forward to the next article regarding oAuth integrations with the callback and indentity URL.

    Currently I’m playing around trying to get an integration working with a POS system, but having difficulty with the Magento 2 way of things.

  5. Hi Tomas,

    Not sure if that’s the one I am looking for. But will definitely give a try.
    Main thing what I am trying to do is to login the mobile user using SOAP webservice if they enter the username and password, just like we have in web: /customer/account/login.

    Let me if that’s for the same purpose.

  6. Do you know how to authenticate customer via SOAP in Magento2? I didn’t see any relevant services.
    Please do share if there’s any workaround.

    1. Hi Raj,
      Is this it?

      
      < ?php
      $request = new SoapClient("http://magento.m2/index.php/soap/?wsdl&services=integrationCustomerTokenServiceV1", array("soap_version" => SOAP_1_2));
      $token = $request->integrationCustomerTokenServiceV1CreateCustomerAccessToken(array("username"=>"tomas@inchoo.net", "password"=>"mypass"));
      var_dump($token->result);
      
      

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.