Magento 2 API usage with examples

Magento 2 API usage with examples

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

Feel free to get in touch if you need any tips&tricks on dealing with Magento 2! We would love to offer you a custom detailed report based on our technical audit!

Related Inchoo Services

You made it all the way down here so you must have enjoyed this post! You may also like:

Custom API for Magento 2 Davor Simek
Davor Simek, | 29

Custom API for Magento 2

How to configure Magento REST and oAuth settings Darko Goles
Darko Goles, | 26

How to configure Magento REST and oAuth settings

Introduction to Magento REST and oAuth Darko Goles
Darko Goles, | 11

Introduction to Magento REST and oAuth

44 comments

  1. Hi, need help this with: string(61) “{“message”:”The signature is invalid. Verify and try again.”}”

    I am trying to setup the OAuth-based authentication, because I am using the 2FA and cannot login with Web API.

  2. Hi Tomas,

    could you tell me how have you found out that you have to use those functions like base64_encode
    urlEncodeAsZend and rawurlencode shaping signature and why they are necessary?
    There’s nothing about that in magento related devdocs pages.

    Thanks.
    Larry

  3. hi all,

    I’m trying to integration Magento – salesforce using Rest API callout. I’m getting Invalid signature error while using this Query ” http://host/shopname/rest/V1/products/?searchCriteria%5Bfilter_groups%5D%5B0%5D%5Bfilters%5D%5B0%5D%5Bfield%5D=updated_at&searchCriteria%5Bfilter_groups%5D%5B0%5D%5Bfilters%5D%5B0%5D%5Bvalue%5D=“2018-08-24 00:00:00 ”

    But if I use this query I’m getting response without any error ” http://host/shopname/rest/V1/products/?searchCriteria=0
    please guide me to solve this issue.

  4. Hi Thomas,

    Can you please look into this I am facing the issue to Authenticate via OAuth based Authentication

    OAuth-based authentication method having error {“message”:”Consumer is not authorized to access %resources”,”parameters”:{“resources”:”Inchoo_Hello:: hello”}
    When I assign ACL resource in {“resources”:”Inchoo_Hello:: hello”} in webapi.xml.

    Please suggest the best solution to authenticate REST API without entering the CallBack URL and Endpoint URL

    Regards
    Deepak

  5. Does anyone fixed the ‘invalid signature’ error when trying to get products on Magento 2.2?

    /V1/products?searchCriteria[filter_groups][0][filters][0][field]=sku&searchCriteria[filter_groups][0][filters][0][value]=0000,0001,0002&searchCriteria[filter_groups][0][filters][0][condition_type]=in

    Thanks

  6. Both Token-based authentication and OAuth-based authentication method having error {“message”:”Consumer is not authorized to access %resources”,”parameters”:{“resources”:”Magento_Customer::customer”}

    1. Hi Guys,

      Everybody getting the following error:

      {“message”:”Consumer is not authorized to access %resources”,”parameters”:{“resources”:”Magento_Customer::customer”}

      You should activate the OAUTH application in the admin panel like it says in the article. That fixed it for me.

  7. Nice Article… Thanks… Please do the following corrections in this post..

    CUsRLOPT_POSTFIELDS => CURLOPT_POSTFIELDS
    Content-Lenght => Content-Length

  8. Handy post! Typo, though: PHP Notice: Use of undefined constant CUsRLOPT_POSTFIELDS – assumed ‘CUsRLOPT_POSTFIELDS’ in php shell code on line 1

    Think you meant ‘CURLOPT_POSTFIELDS’

  9. Hi,

    What is username and password here.

    How can I generate it. Can you please help and show me the steps to create username and pasword

  10. Hi Tomas,
    I want to fetch Magento revenue through API. I am only fetching orders. how can I fetch revenue from Magento. please send me the code. our code is “fetch_order”, “password” => “test123”);
    $ch = curl_init(“http://testrexecom.humcommerce.com/index.php/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-Lenght: ” . strlen(json_encode($userData))));

    $token = curl_exec($ch);

    $ch = curl_init(“http://testrexecom.humcommerce.com/index.php/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=created_at&searchCriteria[filter_groups][0][filters][0][value]=2017-01-02 05:40:00.0000000Z&searchCriteria[filter_groups][0][filters][0][condition_type]=from&searchCriteria[filter_groups][1][filters][0][field]=created_at&searchCriteria[filter_groups][1][filters][0][value]=2017-11-23T11:06:00.0000000Z&searchCriteria[filter_groups][1][filters][0][condition_type]=to&searchCriteria[currentPage]=1&searchCriteria[pageSize]=100”);
    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);

    $result = json_decode($result, 1);
    echo ‘

    ';print_r($result);
  11. For getting customer detail which service should i use for soap. I am unable to get the services in it and the services i am using in may cases its showing message like SOAP-ERROR: Parsing WSDL.

  12. Great tuto.

    There’s a typo you might want to fix though : in the REST code sample, you wrote “Content-Lenght” instead of “Content-Length”. You might want to change that.

  13. Thank you very much for sharing your knowledge. OAuth-based authentication works as you described.

  14. json_decode($token) Tokens are NOT expressed in JSON.. You will get something like quoted string “\”abcd12345\”” as a token. All REST api calls give valid json, except….{List all magento 2 fuck-ups}

  15. Thank you so much. I was struggling with oauth authentication from past two days.
    This code worked instantly.

  16. I used first example and I get this response:
    {“message”:”Consumer is not authorized to access %resources”,”parameters”:{“resources”:”Magento_Customer::customer”}}

    token is created with no issue

    you can check the example here

    http://www.cloudpos.mx/ejemplo.php

    Any advise with this?

    Thanks in advance

  17. Hi Tomas,
    i tried with above script for generating token for SOAP API but it returns below error ‘”Fatal error: Uncaught SoapFault exception: [SOAP-ENV:Server] SoapServer::SoapServer(): Invalid parameters in /var/www/html/magento2011/test.php:17 Stack trace: #0 /var/www/html/magento2011/test.php(17): SoapClient->__call(‘cmsBlockReposit…’, Array) #1 {main} thrown in /var/www/html/magento2011/test.php on line 17″

  18. I have tried the first example and it doesn’t works for me.

    (Please only activate this reply, not the last reply… the first was wrong.)

     "ADMIN", "password" => "PASSWORD");
    $ch = curl_init("https://domain.com/index.php/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);
    
    $ch = curl_init("https://domain.com/index.php/rest/V1/orders?searchCriteria[filter_g‌​roups][0][filters][0‌​][field]=stat‌​‌​us&searchCriteria[filter_groups][0][filters][0][value]=complete");
    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);
    
    echo $result;
    

    This is the error: “Property “FilterG‌​roups” does not have corresponding setter in class “Magento\Framework\Api\SearchCriteria”.”

    Any idea?

  19. Hello Tomas,
    We cant seem to add a customer’s date of birth at registration via REST, have you had any luck with it? also have you seen anyone able to configure Paypal checkout via REST ? our frontend is react native.

  20. hi all can any one help with to call Magento api with Dot net code v 2 version code tryed one
    Magento-RestApi-master on net not able to login also

  21. Please correct a small typo by doing a find/replace of “Content-Lenght” with “Content-Length”

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

    
    $request = new SoapClient("https://inchoo.net: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 = 'https://inchoo.net: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!

    1. I am not able to run this code, i try on my instance its return “Internal Error. Details are available in Magento log file. Report ID: webapi-58de9c8687de2”

      and expection

      Message: Class “array” does not exist. Please note that namespace must be specified.’ in \Magento2cloud\vendor\magento\framework\Webapi\ErrorProcessor.php:195

      how can i procced ?

  23. 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

    2. I have same issue , the encode function works ? I am not sure .. because everybody says it is an encode problem ..

      could you guys share here if you find a solution ?

  24. 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.

  25. 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.

  26. 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.

  27. 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?

      
       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>.

Tell us about your project

Drop us a line. We'd love to know more about your project.