need to call Magento2 rest api in code level how to call default magento REST APIS
3 Answers
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" => "USERNAMe", "password" => "PASSWORD");
$ch = curl_init("http://www.YOUR_DOMIAN.com/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://www.YOUR_DOMIAN.com/rest/V1/products/LC515");
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);
Note :- make sure username is admin user with proper resources should be assigned
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 = '0b3d76jra3log3i2dthslvf0fg54avjv';
$consumerSecret = 'yk8ypwrqrjepa01g3bt0f57ii6kgkqb4';
$accessToken = 'pjhpgtv3un78h83wmhcbk0s8nuxbfhx0';
$accessTokenSecret = 'ryf7sqesnrsn23aifragqywttbm3gkch';
$method = 'GET';
$url = 'http://www.YOUR_DOMIAN..com/rest/V1/products/LC515';
//
$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);
few API we need to use searchCriteria ex :-
GET http://<magento_host>/index.php/rest/V1/products?
searchCriteria[filter_groups][0][filters][0][field]=name&
searchCriteria[filter_groups][0][filters][0][value]=%25Leggings%25&
searchCriteria[filter_groups][0][filters][0][condition_type]=like&
searchCriteria[filter_groups][0][filters][1][field]=name&
searchCriteria[filter_groups][0][filters][1][value]=%25Parachute%25&
searchCriteria[filter_groups][0][filters][1][condition_type]=like
refer http://devdocs.magento.com/guides/v2.1/howdoi/webapi/search-criteria.html
-
Please visit here to see my problem:- magento.stackexchange.com/q/260229/49733 Commented Feb 2, 2019 at 11:32
-
-
What version Magento was this screenshot made in ? I can't locate this page. Commented Dec 13, 2018 at 14:51
-
@AdamJones that's Postman in the screenshot, not the Magento 2 backend. Commented Mar 2, 2019 at 17:40
To complete the example already given, but use the get parameters in the url, use:-
$consumerKey = '2f5jp18p92au5bdfjwp686_somemore';
$consumerSecret = 'x1b48mz2pg1do7gi42aqeb1_somemore';
$accessToken = 'o5msvni7j79t79tl09u18x6_somemore';
$accessTokenSecret = 'f9uhqbf4ym6rv4jdxyymt0u_somemore';
function sign($method, $url, $data, $get, $consumerSecret, $tokenSecret){
$data = array_merge($data,$get);
ksort($data);
$url = str_replace('%7E', '~', rawurlencode($url));
$data = str_replace('%7E', '~', rawurlencode(http_build_query($data, '', '&')));
$data = implode('&', [$method, $url, $data]);
$secret = implode('&', [$consumerSecret, $tokenSecret]);
return base64_encode(hash_hmac('sha1', $data, $secret, true));
}
$method = 'GET';
$url = 'https://your.host/rest/V1/customers/search';
$params =[
'search_criteria[filter_groups][0][filters][0][field]' => 'firstname',
'search_criteria[filter_groups][0][filters][0][value]' => '%dallas%',
'search_criteria[filter_groups][0][filters][0][condition_type]' => 'like',
'search_criteria[filter_groups][1][filters][0][field]' => 'lastname',
'search_criteria[filter_groups][1][filters][0][value]' => '%clarke%',
'search_criteria[filter_groups][1][filters][0][condition_type]' => 'like',
];
//$url = 'https://your.host/rest/V1/products/sku';
//$params = [];
$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, $params, $consumerSecret, $accessTokenSecret);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_URL => $url.'?'.http_build_query($params),
CURLOPT_HTTPHEADER => [
'Authorization: Basic '. base64_encode('not:telling'),
'Authorization: OAuth ' . http_build_query($data, '', ',')
]
]);
$result = curl_exec($curl);
curl_close($curl);
var_dump($result);