For basic Rest API follow steps.
Step1:
Create webapi.xml
Create di.xml
Create Model file under Model directory
Create interface under Api directory
OAuth-based authentication
Token-based authentication
Session-based authentication
OAuth-based authentication :
OAuth authentication is applicable only when working with Integrations. So in order to write a test script using OAuth, an Integration needs to be created with which to interact. For this Go to System > Integrations and clicking on the ‘Add New Integration’ button.After Activating this API.You will get consumer key secret key etc. In API Tab you will select API type.Then set this type in webapi.xml as below.
In token-based authentication, First, you need to authenticate the user and get the token from Magento 2.After getting token you have to pass this token to every request you performed.
Step1:
Create webapi.xml
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/urlname/id/:id" method="GET">
<service class="NameSpace\ModuleName\Api\InterfaceName" method="MethodName"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>
Step2:Create di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="NameSpace\ModuleName\Api\InterfaceName" type="NameSpace\ModuleName\Model\ModelClassName" />
</config>
Step3:Create Model file under Model directory
namespace NameSpace\ModuleName\Model;
use NameSpace\ModuleName\Api\InterfaceName;
class ModelClassName implements InterfaceName
{
protected $merchandisingUploadProductsFactory;
protected $helper;
public function __construct(
\NameSpace\otherModule\Helper\Data $helper )
{
$this->helper = $helper;
}
public function MethodName($var) {
$result = array();
/*
Code
*/
return $result;
}
}
Step4:Create interface under Api directory
namespace NameSpace\ModuleName\Api;
interface InterfaceName
{
public function MethodName($saleId);
}
API authentication can be done in three waysOAuth-based authentication
Token-based authentication
Session-based authentication
OAuth-based authentication :
OAuth authentication is applicable only when working with Integrations. So in order to write a test script using OAuth, an Integration needs to be created with which to interact. For this Go to System > Integrations and clicking on the ‘Add New Integration’ button.After Activating this API.You will get consumer key secret key etc. In API Tab you will select API type.Then set this type in webapi.xml as below.
<resource ref="Magento_Cms::block"/>
Now hit this api with below script :$consumerKey = 'snevl8otqwfn9awdgdy49uwedt2ugx3q1';
$consumerSecret = 'bs114uma7qprlw13vj819a8hjt1lfv8h';
$accessToken = 'llkbo4m36axbl9xf5t83wjvq2gus7w3w';
$accessTokenSecret = 'f1k4ayenyy5ir1fnaa4hl61pltvm9dyh';
$method = 'GET';
$url = 'http://BASE_URL:3100/rest/V1/apiname/saleId/1';
//
$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'] = signDoc($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);
function signDoc($method, $url, $data, $consumerSecret, $tokenSecret)
{
$url = urlEncode($url);
$data = urlEncode(http_build_query($data, '', '&'));
$data = implode('&', [$method, $url, $data]);
$secret = implode('&', [$consumerSecret, $tokenSecret]);
return base64_encode(hash_hmac('sha1', $data, $secret, true));
}
function urlEncode($value)
{
$encoded = rawurlencode($value);
$encoded = str_replace('%7E', '~', $encoded);
return $encoded;
}
Token-based authentication:In token-based authentication, First, you need to authenticate the user and get the token from Magento 2.After getting token you have to pass this token to every request you performed.
$adminUrl='http://fe-magento-2-erp.co.uk:3100/index.php/rest/V1/integration/admin/token';
$ch = curl_init();
$data = array("username" => "userid", "password" => "password");
$data_string = json_encode($data);
$ch = curl_init($adminUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
// Pass Token to API...
$token = curl_exec($ch);
$ch = curl_init("http://fe-magento-2-erp.co.uk:3100/rest/V1/apiname/saleId/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);
Comments
Post a Comment