Joshua
Joshua

Reputation: 11

Get product details in JSON format using REST API

How to get the product details in JSON format using REST API in Magento2? When I search I found the following code.

$url = 'magentohost url';
$callbackUrl = $url . "oauth_admin.php";
$temporaryCredentialsRequestUrl = $url . "oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = $url . 'admin/oauth_authorize';
$accessTokenRequestUrl = $url . 'oauth/token';
$apiUrl = $url . 'api/rest';
$consumerKey = 'consumer_key';
$consumerSecret = 'consumer_secret';
$token = 'token';
$secret = 'token_secret';
 try {
    $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
    $oauthClient->setToken($token, $secret);
    $resourceUrl = "$apiUrl/products";
    $oauthClient->fetch($resourceUrl, array(), 'GET', array('Content-Type' => 'application/json', 'Accept' => 'application/json'));
    $productsList = json_decode($oauthClient->getLastResponse());
    echo '<pre>';
    print_r($productsList);
}
catch(Exception $e) {
    echo '<pre>';
    print_r($e);
}

But where I need to put this query... And also I am confusing with the URL... And also it returns error Class OAuth not found

Upvotes: 1

Views: 1539

Answers (1)

Delroy Brown
Delroy Brown

Reputation: 29

First, we need to create Web Service Role and Web Service User in Magento 2

Create Web Service Role:
Login Admin Panel> System> User Roles> Add New Role
Add the Role Name and your current password of Admin in Your Password field
Tap Role Resources
Choose what are required for service of your web in Resource Access
Tap Save Role
Create Web Service User in Magento 2

This user is used for the role you’ve created

Go to System> All Users> Add New User
Fill in all the necessary information
Tap User Role then choose which you’ve created
Tap Save User

The user above will used to REST API web service in Magento 2.

Next, we will get starting with Magento 2 REST API. Create a php file called my_magento2_rest_apt.php or whatever you want to make it. and place it in the magneto root directory.

Add this code into the file.

define('BASEURL','http://yourdomin.com/magento2location/');

$apiUser = 'username'; 
$apiPass = 'password';
$apiUrl = BASEURL.'index.php/rest/V1/integration/admin/token';
/*
    Magento 2 REST API Authentication
*/
$data = array("username" => $apiUser, "password" => $apiPass);                                                                    
$data_string = json_encode($data);                       
try{
    $ch = curl_init($apiUrl); 
    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))                                                                       
    );       
    $token = curl_exec($ch);
    $token = json_decode($token);
    if(isset($token->message)){
        echo $token->message;
    }else{
        $key = $token;
    }
}catch(Exception $e){
    echo 'Error: '.$e->getMessage();
}


/*
    Get Product By SKU REST API Magento 2
    Use above key into header
*/
$headers = array("Authorization: Bearer $key"); 
//$requestUrl = BASEURL.'index.php/rest/V1/products/24-MB01';//24-MB01 is the sku.
//$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria[page_size]=10';// get total 10 products
//$requestUrl = BASEURL.'index.php/rest/V1/categories/24/products';// 24 category id
//$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria=';//get all products
$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=24&searchCriteria[filter_groups][0][filters][0][condition_type]=eq';

$ch = curl_init();
try{
    $ch = curl_init($requestUrl); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   

$result = curl_exec($ch);
$result = json_decode($result);

if(isset($result->message)){
    echo $result->message;
}else{
    print_r($result);
}
    }catch(Exception $e){
        echo 'Error: '.$e->getMessage();
    }

now to get to your API just type. http://yourdomin.com/magento2location/my_magento2_rest_apt.php

Upvotes: 1

Related Questions