Magento 2 API usage with examples

Related Inchoo Services

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

$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);

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":"","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

$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(
                '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:

array(1) {
  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:

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

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 (
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:

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;
$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_URL => $url,
		'Authorization: OAuth ' . http_build_query($data, '', ',')
$result = curl_exec($curl);

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":"","firstname":"Tomas","lastname":"Novoselic","store_id":1,"website_id":1,"addresses":[],"disable_auto_group_change":0}"


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:

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!

Published in:
Leave a comment

Tomas Novoselic

- Backend Developer

At Inchoo, Tomas is backend developer, 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


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

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

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

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

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

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

    Any advise with this?

    Thanks in advance

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

  8. 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("");
    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("[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?

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

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

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

  12. 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(
                    '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();

    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 ?

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


    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 ?

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

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

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

  17. 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"=>"", "password"=>"mypass"));

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