Shipping Address API: Customer Shipping Details Using API in Magento 2

I am going to explain how you can get the customer details by using customer shipping address API integration.

Our Magento development team has developed a module that helps you to retrieve the information of customer ID.

So by using this module help you through the entire shipping address information to show on the frontend on any kind of website like you can show it on react js website or node js website.

Magento 2 Shipping Address API

 

Why Shipping Address APIs?

No more complicated code is required for integration.

Wishusucess offers you to get customer shipping orders information by using the ShippingAddressApi.

You just have to call the API on your other website and then you will get the details of your customer ID.

 

Step 1: Shipping API Registration

app/code/Wishusucess/ShippingAddress/registration.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_ShippingAddress',
__DIR__
);

 

Step 2: Module Name & Information

app/code/Wishusucess/ShippingAddress/etc/module.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_ShippingAddress" setup_version="1.0.9" />
</config>

 

Step 3: Give Preference of API

This dependency injection file decide the dependency of your custom module. So this module has custom dependencies that going to injected by the object manager. We can also configure the setting but here that is not necessary.

app/code/Wishusucess/ShippingAddress/etc/di.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Wishusucess\ShippingAddress\Api\CustomInterface" type="Wishusucess\ShippingAddress\Model\Api\Custom"/>
</config>

 

Step 3: Route Method And URL

Route URL used to decide the URL of your API and method decide what kind of operation we are going to perform so, here i have given /V1/wishusucess/shippingaddress/ route URL and i am using GET method to receive the information using API calls.

app/code/Wishusucess/ShippingAddress/etc/webapi.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<route method="GET" url="/V1/wishusucess/shippingaddress/">
<service class="Wishusucess\ShippingAddress\Api\CustomInterface" method="getPost"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>

 

Step 4: Decide Route ID

Here you can decide the frontend id of your shipping address module by using the route id, So i have given route id shipping for this module.

app/code/Wishusucess/ShippingAddress/etc/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
<route id="shipping" frontName="shipping">
<module name="Wishusucess_ShippingAddress" />
</route>
</router>
</config>

 

Step 5: Shipping Address API Model Class

app/code/Wishusucess/ShippingAddress/Model/Api/Custom.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\ShippingAddress\Model\Api;

use Psr\Log\LoggerInterface;

class Custom 
{
/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;
protected $_customerFactory;
protected $_addressFactory;

public function __construct(
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Model\AddressFactory $addressFactory,
array $data = []
) {
$this->resultPageFactory = $resultPageFactory;
$this->_customerFactory = $customerFactory;
$this->_addressFactory = $addressFactory;



}

/**
* @inheritdoc
*/

public function getPost($customerId)
{
$response = ['success' => false];

try {
$customer = $this->_customerFactory->create()->load($customerId); //insert customer id

//billing
$billingAddressId = $customer->getDefaultBilling();
$billingAddress = $this->_addressFactory->create()->load($billingAddressId);


//shipping
$shippingAddressId = $customer->getDefaultShipping();
$shippingAddress = $this->_addressFactory->create()->load($shippingAddressId);

$field_data['ShippingAddress']=$shippingAddress->getData();
$field_data['BillingAddress']=$billingAddress->getData();

$response= $field_data;
// print_r($cart);


} catch (\Exception $e) {
$response = ['success' => false, 'message' => $e->getMessage()];
}
$returnArray = $response;
return $returnArray; 
}
}

 

Step 6: Controller To Execute API

Now here we have to get the customer id and then initialize that customer id in $customerId and then we have to load that customer id in $customer now we can find the customer shipping information and customer billing information from $customer.

Then execute() method will return after the execution of the getDefaultBilling() and getDefaultShipping().

app/code/Wishusucess/ShippingAddress/Controller/Index/Index.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\ShippingAddress\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action {

/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;
protected $_customerFactory;
protected $_addressFactory;
protected $_data;


public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Model\AddressFactory $addressFactory,
array $data = []
) {
$this->_customerFactory = $customerFactory;
$this->_data = $data;
parent::__construct($context);
}

public function execute() {
$customerId=41;
$customer = $this->_customerFactory->create()->load($customerId); //insert customer id

//billing
$billingAddressId = $customer->getDefaultBilling();
$billingAddress = $this->_addressFactory->create()->load($billingAddressId);


//shipping
$shippingAddressId = $customer->getDefaultShipping();
$shippingAddress = $this->_addressFactory->create()->load($shippingAddressId);


echo "<pre>";

print_r($customer->getData());

echo "------------------------";
// print_r($shippingAddress->getData());

die();

}

}

 

Step 7: API for Custom Interface

app/code/Wishusucess/ShippingAddress/Api/CustomInterface.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\ShippingAddress\Api;

interface CustomInterface
{
/**
* GET for Post api
* @param string $customerId Customer id.
* @return boolean|array
*/

public function getPost($customerId);
}

 

So when you open your customer account summary on the Magento 2 website, which appears on the right of the Account Details page. It shows shipping addresses and billing addresses that also have the manage addresses on the customer page.

So by using this module you can get all these details through API calls on your other site. and from there you can edit the information, delete the information and add the new address by using different methods.

Here I have used only the GET method to retrieve the information but in order to perform other operations you have to use POST, DELETE, PUT, SAVE etc as per your requirement.

 

Download API

Related Post:

Latest Products API: Magento 2 Get Latest Products Using REST API Call

CMS REST API: Retrieve Magento 2 CMS Pages & Block Data Using API

 

Recommend Post:

Elasticsearch: How to Install Elasticsearch in Ubuntu 18.04

 

 

 

 

Latest Products API: Magento 2 Get Latest Products Using REST API Call

In this Wishusucess custom API development of module series, I am going to explain how you can get all the latest products of the Magento 2 website on other websites using the latest products API call.

Wishusucess Magento 2 expert developer has developed a module which is Wishusucess_LatestProductsApi that will help you to get load all your products just by calling the API.

 

Create Product Yes/No Attribute

first I have created a product yes no attributes in Admin > Stores > Attributes > Product.

Now there I have decided an identifier that is latestproducts, now I am going to use this identifier in the controller and model class of this custom Magento 2 Latest Products yes/no attributes model.

At the end of module, we can get all collections just by rest API call on any other website.

 

Step 1: Registration of LatestProductsApi

app/code/Wishusucess/LatestProductsApi/registration.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_LatestProductsApi',
__DIR__
);

 

Step 2: Module Basic Information

app/code/Wishusucess/LatestProductsApi/etc/module.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_LatestProductsApi" setup_version="1.0.0" />
</config>

 

Step 3: Declare Dependency of Module

app/code/Wishusucess/LatestProductsApi/etc/di.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Wishusucess\LatestProductsApi\Api\CustomInterface" type="Wishusucess\LatestProductsApi\Model\Api\Custom"/>
</config>

 

Step 4: Latest Products API Routing URL

Here, I have decided on a routing method GET and route URL, and also I have added a custom service class which I have implemented in our custom module.

app/code/Wishusucess/LatestProductsApi/etc/webapi.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<route method="GET" url="/V1/wishusucess/latestproductsapi/">
<service class="Wishusucess\LatestProductsApi\Api\CustomInterface" method="getPost"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>

 

Step 6: Routes URL ID

app/code/Wishusucess/LatestProductsApi/etc/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
<route id="latestproductsapi" frontName="latestproductsapi">
<module name="Wishusucess_LatestProductsApi" />
</route>
</router>
</config>

 

Step 7: Controller Index File

Now, here I have added custom product attribute latestproducts in the controller class so that attribute filter the product based on 1 and 0 value of the attribute.

app/code/Wishusucess/LatestProductsApi/Controller/Index/Index.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\LatestProductsApi\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action {

/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;
protected $data;

public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
array $data = []
) {
$this->_productCollectionFactory = $productCollectionFactory; 
$this->catalogProductVisibility = $catalogProductVisibility;
$this->data = $data;
parent::__construct($context);
}

public function execute() {
$collection = $this->_productCollectionFactory->create();
$collection = $this->_productCollectionFactory->create()->addAttributeToSelect('*')->addAttributeToFilter('status', '1')
->addAttributeToFilter('latestproducts', '1');

$collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());
$response = $collection;

echo "<pre>";
// print_r($response->getData());
$cart = array();
foreach($response as $value)
{
$cart[] = $value->getData();
}

print_r($cart);
die();

}

}

 

Step 8: Model Class Latest Products API

app/code/Wishusucess/LatestProductsApi/Model/Api/Custom.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\LatestProductsApi\Model\Api;

use Psr\Log\LoggerInterface;

class Custom 
{
/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;

public function __construct(
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
array $data = []
) {
$this->resultPageFactory = $resultPageFactory;
$this->_productCollectionFactory = $productCollectionFactory; 
$this->catalogProductVisibility = $catalogProductVisibility;


}

/**
* @inheritdoc
*/

public function getPost()
{
$response = ['success' => false];

try {

$collection = $this->_productCollectionFactory->create();
$collection = $this->_productCollectionFactory->create()->addAttributeToSelect('*')->addAttributeToFilter('status', '1')
->addAttributeToFilter('latestproducts', '1');

$collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());
$result= $collection;
$cart = array();
foreach($result as $value)
{
$cart[] = $value->getData();
}
$response= $cart;
// print_r($cart);


} catch (\Exception $e) {
$response = ['success' => false, 'message' => $e->getMessage()];
}
$returnArray = $response;
return $returnArray; 
}
}

 

Step 9: Latest Products API Interface

app/code/Wishusucess/LatestProductsApi/Api/CustomInterface.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\LatestProductsApi\Api;

interface CustomInterface
{
/**
* GET for Post api
* @return boolean|array
*/

public function getPost();
}

 

Now Run Bellow Command:

php/bin magento setup:upgrade

php/bin magento setup:di:compile

php/bin magento setup:static-content:deploy -f

php/bin magento c:c

 

Now, I am going to test this module using the postman API tool.

So, first I will create an admin access token by using the below Magento 2 admin API.

https://wishusucess.com/rest/store_id/V1/integration/admin/token

Magento 2 Admin Access Token

Now we have received the admin access token so we will use this token to authorize the API request.

So I am going to add this token to the header section.

Authorization: Bearer Token

Content-Type: application/JSON

Method: POST

Payload: Not Required

Authorise Your Request With Token

Now with the admin access token, I am using this implemented token.

https://wishusucess.com/rest/store_id/V1/sparx/latestproduct/

So all the enabled lasted product is loading here.

Call Latest Products API

Related Post:

How To GET Products List Using Magento 2 REST API

How To Get Product Image URL Using REST API in Magento 2

How To Get Category List By REST API and GraphQL In Magento 2, E.g.

 

Recommended Post:

Elasticsearch: How to Install Elasticsearch in Ubuntu 18.04

Download Latest Product Custom Module on GitHub

 

CMS REST API: Retrieve Magento 2 CMS Pages & Block Data Using API

I am going to explain how we can load Magento 2 cms block content and cms page content on another website. By Using Wishusucess CMS REST API you can easily get the data to delete the data of your page and block.

Magento 2 CMS REST API

This module contains the only GET method but you can perform all kinds of getting operations over the cms page and cms block of your stores.

You can search page content by using the below route URL.

http://wishusucess.com/rest/all/V1/wishusucess/cmsPage/search

And for the block content search, you can use the below URL.

http://wishusucess.com/rest/all/V1/wishusucess/cmsBlock/search

For getting the whole cms page content we have to use below route URL of the cms page API

http://wishusucess.com/rest/store_id/V1/wishusucess/cmsPage/:pageId

The whole content of the block we can get by using below CMS Block REST API

http://wishusucess.com/rest/store_id/V1/wishusucess/cmsBlock/:blockId

 

Searching Using CMS REST API

We have also included the search content features using rest API on other websites. So you can easily call that API on any site and that will allow you to search the content of block and page.

You have to fill that search criterion to get the content of the block or page.

 

Available Endpoints Wishusucess_CMSApi

By using the following endpoint you can perform your desire action over the data on any website.

You just have to call the below endpoints:

http://wishusucess.com/rest/store_id/rest/V1/Wishusucess/cmsPage/:pageId

You can retrieves page information based on the page id

http://wishusucess.com/rest/store_id/rest/V1/Wishusucess/cmsPage/search

We can perform data retrieves operation on the list of pages.

http://wishusucess.com/rest/store_id/rest/V1/Wishusucess/cmsPageIdentifier/:identifier/storeId/:storeId

By giving integer value on page id we can get page content.

http://wishusucess.com/rest/store_id/rest/V1/Wishusucess/cmsBlock/:blockId

Can retrieve Magento 2 cms block data by giving block id.

http://wishusucess.com/rest/store_id/rest/V1/Wishusucess/cmsBlockIdentifier/:identifier/storeId/:storeId

Magento 2 cms block needs an identifier (string value) to get the block content using this REST API.

http://wishusucess.com/rest/store_id/rest/V1/Wishusucess/cmsBlock/search

Can get all the list of blocks on any website by using the above block rest API.

 

 

Step 1: Registration CMSApi

app/code/Wishusucess/CmsApi/registration.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_CmsApi',
__DIR__
);

 

Step 2: Basic Information About CMSApi

app/code/Wishusucess/CmsApi/etc/module.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_CmsApi" setup_version="0.1.0">
</module>
</config>

 

Step 3: Dependency Injection of Module CMSApi

app/code/Wishusucess/CmsApi/etc/di.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Wishusucess\CmsApi\Api\PageManagerInterface"
type="Wishusucess\CmsApi\Model\PageManager" />
<preference for="Wishusucess\CmsApi\Api\BlockManagerInterface"
type="Wishusucess\CmsApi\Model\BlockManager" />
<preference for="Wishusucess\CmsApi\Api\Data\BlockInterface"
type="Wishusucess\CmsApi\Model\Block" />
<preference for="Wishusucess\CmsApi\Api\Data\PageInterface"
type="Wishusucess\CmsApi\Model\Page" />
<preference for="Wishusucess\CmsApi\Api\Data\PageSearchResultsInterface"
type="Magento\Framework\Api\SearchResults" />
<preference for="Wishusucess\CmsApi\Api\Data\BlockSearchResultsInterface"
type="Magento\Framework\Api\SearchResults" />
<type name="Wishusucess\CmsApi\Model\BlockManager">
<arguments>
<argument name="collectionProcessor" xsi:type="object">Magento\Cms\Model\Api\SearchCriteria\BlockCollectionProcessor</argument>
</arguments>
</type>
<type name="Wishusucess\CmsApi\Model\PageManager">
<arguments>
<argument name="collectionProcessor" xsi:type="object">Magento\Cms\Model\Api\SearchCriteria\PageCollectionProcessor</argument>
</arguments>
</type>
</config>

 

Step 4: Route URL of CMS REST API

app/code/Wishusucess/CmsApi/etc/webapi.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<!-- Cms Page -->
<route url="/V1/wishusucess/cmsPage/:pageId" method="GET">
<service class="Wishusucess\CmsApi\Api\PageManagerInterface" method="getById"/>
<resources>
<resource ref="Magento_Cms::page"/>
</resources>
</route>
<route url="/V1/wishusucess/cmsPageIdentifier/:identifier/storeId/:storeId" method="GET">
<service class="Wishusucess\CmsApi\Api\PageManagerInterface" method="getByIdentifier"/>
<resources>
<resource ref="Magento_Cms::page"/>
</resources>
</route>
<route url="/V1/wishusucess/cmsPage/search" method="GET">
<service class="Wishusucess\CmsApi\Api\PageManagerInterface" method="getList"/>
<resources>
<resource ref="Magento_Cms::page"/>
</resources>
</route>
<!-- Cms Block -->
<route url="/V1/wishusucess/cmsBlock/:blockId" method="GET">
<service class="Wishusucess\CmsApi\Api\BlockManagerInterface" method="getById"/>
<resources>
<resource ref="Magento_Cms::block"/>
</resources>
</route>
<route url="/V1/wishusucess/cmsBlockIdentifier/:identifier/storeId/:storeId" method="GET">
<service class="Wishusucess\CmsApi\Api\BlockManagerInterface" method="getByIdentifier"/>
<resources>
<resource ref="Magento_Cms::block"/>
</resources>
</route>
<route url="/V1/wishusucess/cmsBlock/search" method="GET">
<service class="Wishusucess\CmsApi\Api\BlockManagerInterface" method="getList"/>
<resources>
<resource ref="Magento_Cms::block"/>
</resources>
</route>
</routes>

 

Step 5: CMSApi Block Model

app/code/Wishusucess/CmsApi/Model/Block.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\CmsApi\Model;

use Wishusucess\CmsApi\Api\Data\BlockInterface;

class Block extends \Magento\Cms\Model\Block implements BlockInterface
{
/**
* @inheritdoc
*/
public function getStoreId()
{
return $this->_getData(self::STORE_ID);
}

/**
* @inheritdoc
*/
public function setStoreId(array $storeIds)
{
$this->setData(self::STORE_ID, $storeIds);

return $this;
}
}

 

Step 6: Model Class for Block Manager

app/code/Wishusucess/CmsApi/Model/BlockManager.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\CmsApi\Model;

use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\Data\BlockInterface;
use Magento\Cms\Model\BlockFactory;
use Magento\Cms\Model\ResourceModel\Block;
use Magento\Cms\Model\Template\FilterProvider;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\App\Emulation;
use Wishusucess\CmsApi\Api\BlockManagerInterface;
use Wishusucess\CmsApi\Api\Data\BlockInterfaceFactory;
use Wishusucess\CmsApi\Api\Data\BlockSearchResultsInterfaceFactory;
use Magento\Framework\App\State;
use Magento\Framework\App\Area;

/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class BlockManager extends ManagerBase implements BlockManagerInterface
{
/**
* @var BlockRepositoryInterface
*/
private $blockRepository;

/**
* @var FilterProvider
*/
private $filterProvider;

/**
* @var BlockFactory
*/
private $blockFactory;

/**
* @var Block
*/
private $blockResource;

/**
* @var BlockSearchResultsInterfaceFactory
*/
private $searchResultsFactory;

/**
* @var Block\CollectionFactory
*/
private $blockCollectionFactory;

/**
* @var CollectionProcessorInterface
*/
private $collectionProcessor;

/**
* @var BlockInterfaceFactory
*/
private $blockDtoFactory;

/**
* @var DataObjectHelper
*/
private $dataObjectHelper;

/**
* @var State
*/
private $appState;

/**
* @var Emulation
*/
private $emulation;

/**
* @param BlockRepositoryInterface $blockRepository
* @param FilterProvider $filterProvider
* @param BlockFactory $blockFactory
* @param Block $blockResource
* @param Block\CollectionFactory $blockCollectionFactory
* @param BlockSearchResultsInterfaceFactory $searchResultsFactory
* @param CollectionProcessorInterface $collectionProcessor
* @param BlockInterfaceFactory $blockDtoFactory
* @param DataObjectHelper $dataObjectHelper
* @param State $appState
* @param Emulation $emulation
*/
public function __construct(
BlockRepositoryInterface $blockRepository,
FilterProvider $filterProvider,
BlockFactory $blockFactory,
Block $blockResource,
Block\CollectionFactory $blockCollectionFactory,
BlockSearchResultsInterfaceFactory $searchResultsFactory,
CollectionProcessorInterface $collectionProcessor,
BlockInterfaceFactory $blockDtoFactory,
DataObjectHelper $dataObjectHelper,
State $appState,
Emulation $emulation
) {
$this->blockRepository = $blockRepository;
$this->filterProvider = $filterProvider;
$this->blockFactory = $blockFactory;
$this->blockResource = $blockResource;
$this->searchResultsFactory = $searchResultsFactory;
$this->blockCollectionFactory = $blockCollectionFactory;
$this->collectionProcessor = $collectionProcessor;
$this->blockDtoFactory = $blockDtoFactory;
$this->dataObjectHelper = $dataObjectHelper;
$this->appState = $appState;
$this->emulation = $emulation;
}

/**
* @inheritdoc
*/
public function getById($blockId)
{
$block = $this->blockRepository->getById($blockId);
$content = $this->getBlockContentFiltered($block->getContent());
$block->setContent($content);

return $block;
}

/**
* @inheritdoc
*/
public function getByIdentifier($identifier, $storeId = null)
{
$block = $this->blockFactory->create();
$block->setStoreId($storeId);
$this->blockResource->load($block, $identifier, BlockInterface::IDENTIFIER);

if (!$block->getId()) {
throw new NoSuchEntityException(
__('CMS Block with identifier "%1" does not exist.', $identifier)
);
}

$content = $this->getBlockContentFiltered($block->getContent());
$block->setContent($content);

return $block;
}

/**
* @inheritdoc
*/
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria)
{
$storeId = $this->getStoreIdBySearchCriteria($searchCriteria);

if ($storeId !== null) {
$this->emulation->startEnvironmentEmulation($storeId);
}

/** @var \Magento\Cms\Model\ResourceModel\Block\Collection $collection */
$collection = $this->blockCollectionFactory->create();
$this->collectionProcessor->process($searchCriteria, $collection);

$items = [];
/** @var \Magento\Cms\Model\Block $block */
foreach ($collection->getItems() as $block) {
$content = $this->getBlockContentFiltered($block->getContent());
$block->setContent($content);
$blockDto = $this->blockDtoFactory->create();
$this->dataObjectHelper->populateWithArray(
$blockDto,
$block->getData(),
\Wishusucess\CmsApi\Api\Data\BlockInterface::class
);
$blockDto->setId($block->getId());
$items[] = $blockDto;
}

$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($searchCriteria);
$searchResults->setItems($items);
$searchResults->setTotalCount(count($items));

if ($storeId !== null) {
$this->emulation->stopEnvironmentEmulation();
}

return $searchResults;
}

/**
* @param string $content
* @return string
*/
private function getBlockContentFiltered($content)
{
$emulatedResult = $this->appState->emulateAreaCode(
Area::AREA_FRONTEND,
[$this->filterProvider->getBlockFilter(), 'filter'],
[$content]
);

return $emulatedResult;
}
}

 

Step 7: CMSApi Model Manager for Search Criteria

app/code/Wishusucess/CmsApi/Model/ManagerBase.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\CmsApi\Model;

use Magento\Framework\Api\SearchCriteriaInterface;

class ManagerBase
{
/**
* @param SearchCriteriaInterface $searchCriteria
* @return int
*/
protected function getStoreIdBySearchCriteria(SearchCriteriaInterface $searchCriteria)
{
$filterGroups = $searchCriteria->getFilterGroups();

$storeIds = [];
foreach ($filterGroups as $filterGroup) {
foreach ($filterGroup->getFilters() as $filter) {
if ($filter->getField() == 'store_id') {
$storeIds = array_merge($storeIds, explode(',', $filter->getValue()));
}
}

if (count($storeIds) > 1) {
return 0; // default store
} else {
// if store_id wasn't passed as a filter,
// we should not continue with store emulation
return null;
}
}

return (int) array_shift($storeIds);
}
}

 

Step 8: CMS API For Page Model

app/code/Wishusucess/CmsApi/Model/Page.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\CmsApi\Model;

use Wishusucess\CmsApi\Api\Data\PageInterface;

class Page extends \Magento\Cms\Model\Page implements PageInterface
{
/**
* @inheritdoc
*/
public function getStoreId()
{
return $this->_getData(self::STORE_ID);
}

/**
* @inheritdoc
*/
public function setStoreId(array $storeIds)
{
$this->setData(self::STORE_ID, $storeIds);

return $this;
}
}

 

Step 9: Page Manager CMS REST API

app/code/Wishusucess/CmsApi/Model/PageManager.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\CmsApi\Model;

use Magento\Cms\Api\Data\PageInterface;
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Cms\Model\PageFactory;
use Magento\Cms\Model\ResourceModel\Page;
use Magento\Cms\Model\Template\FilterProvider;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\App\Emulation;
use Wishusucess\CmsApi\Api\Data\PageInterfaceFactory;
use Wishusucess\CmsApi\Api\Data\PageSearchResultsInterfaceFactory;
use Wishusucess\CmsApi\Api\PageManagerInterface;
use Magento\Framework\App\State;
use Magento\Framework\App\Area;

/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class PageManager extends ManagerBase implements PageManagerInterface
{
/**
* @var PageRepositoryInterface
*/
private $pageRepository;

/**
* @var FilterProvider
*/
private $filterProvider;

/**
* @var PageFactory
*/
private $pageFactory;

/**
* @var Page
*/
private $pageResource;

/**
* @var Page\CollectionFactory
*/
private $pageCollectionFactory;

/**
* @var PageSearchResultsInterfaceFactory
*/
private $searchResultsFactory;

/**
* @var CollectionProcessorInterface
*/
private $collectionProcessor;

/**
* @var PageInterfaceFactory
*/
private $pageDtoFactory;

/**
* @var DataObjectHelper
*/
private $dataObjectHelper;

/**
* @var State
*/
private $appState;

/**
* @var Emulation
*/
private $emulation;

/**
* @param PageRepositoryInterface $pageRepository
* @param FilterProvider $filterProvider
* @param PageFactory $pageFactory
* @param Page $pageResource
* @param Page\CollectionFactory $pageCollectionFactory
* @param PageSearchResultsInterfaceFactory $searchResultsFactory
* @param CollectionProcessorInterface $collectionProcessor
* @param PageInterfaceFactory $pageDtoFactory
* @param DataObjectHelper $dataObjectHelper
* @param State $appState
* @param Emulation $emulation
*/
public function __construct(
PageRepositoryInterface $pageRepository,
FilterProvider $filterProvider,
PageFactory $pageFactory,
Page $pageResource,
Page\CollectionFactory $pageCollectionFactory,
PageSearchResultsInterfaceFactory $searchResultsFactory,
CollectionProcessorInterface $collectionProcessor,
PageInterfaceFactory $pageDtoFactory,
DataObjectHelper $dataObjectHelper,
State $appState,
Emulation $emulation
) {
$this->pageRepository = $pageRepository;
$this->filterProvider = $filterProvider;
$this->pageFactory = $pageFactory;
$this->pageResource = $pageResource;
$this->pageCollectionFactory = $pageCollectionFactory;
$this->searchResultsFactory = $searchResultsFactory;
$this->collectionProcessor = $collectionProcessor;
$this->pageDtoFactory = $pageDtoFactory;
$this->dataObjectHelper = $dataObjectHelper;
$this->appState = $appState;
$this->emulation = $emulation;
}

/**
* @inheritdoc
*/
public function getById($pageId)
{
$page = $this->pageRepository->getById($pageId);
$content = $this->getPageContentFiltered($page->getContent());
$page->setContent($content);

return $page;
}

/**
* @inheritdoc
*/
public function getByIdentifier($identifier, $storeId = null)
{
$page = $this->pageFactory->create();
$page->setStoreId($storeId);
$this->pageResource->load($page, $identifier, PageInterface::IDENTIFIER);

if (!$page->getId()) {
throw new NoSuchEntityException(
__('CMS Page with identifier "%1" does not exist.', $identifier)
);
}

$content = $this->getPageContentFiltered($page->getContent());
$page->setContent($content);

return $page;
}

/**
* @inheritdoc
*/
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria)
{
$storeId = $this->getStoreIdBySearchCriteria($searchCriteria);

if ($storeId !== null) {
$this->emulation->startEnvironmentEmulation($storeId);
}

/** @var \Magento\Cms\Model\ResourceModel\Page\Collection $collection */
$collection = $this->pageCollectionFactory->create();
$this->collectionProcessor->process($searchCriteria, $collection);

$items = [];
/** @var \Magento\Cms\Model\Page $page */
foreach ($collection->getItems() as $page) {
$content = $this->getPageContentFiltered($page->getContent());
$page->setContent($content);
$pageDto = $this->pageDtoFactory->create();
$this->dataObjectHelper->populateWithArray(
$pageDto,
$page->getData(),
\Wishusucess\CmsApi\Api\Data\PageInterface::class
);
$pageDto->setId($page->getId());
$items[] = $pageDto;
}

$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($searchCriteria);
$searchResults->setItems($items);
$searchResults->setTotalCount(count($items));

if ($storeId !== null) {
$this->emulation->stopEnvironmentEmulation();
}

return $searchResults;
}

/**
* @param string $content
* @return string
*/
private function getPageContentFiltered($content)
{
$emulatedResult = $this->appState->emulateAreaCode(
Area::AREA_FRONTEND,
[$this->filterProvider->getPageFilter(), 'filter'],
[$content]
);

return $emulatedResult;
}
}

 

Step 10: Block Manager Class of CMSApi

app/code/Wishusucess/CmsApi/Api/BlockManagerInterface.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\CmsApi\Api;

interface BlockManagerInterface
{
/**
* @param int $blockId
* @return \Magento\Cms\Api\Data\BlockInterface
*/
public function getById($blockId);

/**
* @param string $identifier
* @param int $storeId
* @return \Magento\Cms\Api\Data\BlockInterface
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getByIdentifier($identifier, $storeId = null);

/**
* @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
* @return \Wishusucess\CmsApi\Api\Data\BlockSearchResultsInterface
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);
}

 

Step 11: Page Manager Interface

app/code/Wishusucess/CmsApi/Api/PageManagerInterface.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\CmsApi\Api;

interface PageManagerInterface
{
/**
* @param int $pageId
* @return \Magento\Cms\Api\Data\PageInterface
*/
public function getById($pageId);

/**
* @param string $identifier
* @param int $storeId
* @return \Magento\Cms\Api\Data\PageInterface
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getByIdentifier($identifier, $storeId = null);

/**
* @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
* @return \Wishusucess\CmsApi\Api\Data\PageSearchResultsInterface
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);
}

 

Step 12: Block Interface of API

app/code/Wishusucess/CmsApi/Api/Data/BlockInterface.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\CmsApi\Api\Data;

interface BlockInterface extends \Magento\Cms\Api\Data\BlockInterface
{
/**#@+
* Constants for keys of data array. Identical to the name of the getter in snake case
*/
const STORE_ID = 'store_id';
/**#@-*/

/**
* @return int[]
*/
public function getStoreId();

/**
* @param int[] $storeIds
* @return BlockInterface
*/
public function setStoreId(array $storeIds);
}

 

Step 13: Search Result Interface

app/code/Wishusucess/CmsApi/Api/Data/BlockSearchResultsInterface.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\CmsApi\Api\Data;

use Magento\Framework\Api\SearchResultsInterface;

interface BlockSearchResultsInterface extends SearchResultsInterface
{
/**
* @return \Wishusucess\CmsApi\Api\Data\BlockInterface[]
*/
public function getItems();

/**
* @param \Wishusucess\CmsApi\Api\Data\BlockInterface[] $items
* @return BlockSearchResultsInterface
*/
public function setItems(array $items);
}

 

Step 14: Get Page Store Id

app/code/Wishusucess/CmsApi/Api/Data/PageInterface.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\CmsApi\Api\Data;

interface PageInterface extends \Magento\Cms\Api\Data\PageInterface
{
/**#@+
* Constants for keys of data array. Identical to the name of the getter in snake case
*/
const STORE_ID = 'store_id';
/**#@-*/

/**
* @return int[]
*/
public function getStoreId();

/**
* @param int[] $storeIds
* @return BlockInterface
*/
public function setStoreId(array $storeIds);
}

 

Step 15: Page Search Result Interface

app/code/Wishusucess/CmsApi/Api/Data/PageSearchResultsInterface.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\CmsApi\Api\Data;

use Magento\Framework\Api\SearchResultsInterface;

interface PageSearchResultsInterface extends SearchResultsInterface
{
/**
* @return \Wishusucess\CmsApi\Api\Data\PageInterface[]
*/
public function getItems();

/**
* @param \Wishusucess\CmsApi\Api\Data\PageInterface[] $items
* @return PageSearchResultsInterface
*/
public function setItems(array $items);
}

 

Related Post:

Featured Product API: Get Featured Product Using Magento 2 REST API

How To Call Magento 2 REST API For Customer Account Update

How To GET Products List Using Magento 2 REST API

 

Recommended Post

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

 

Download API

CMS Page REST API: How To Get Data of Magento 2 CMS Page Via API

Today, I am going to explain how you can load your Magento 2 website cms pages data on your other websites using CMS Page REST API.

By using default API to get Magento CMS Page content on the other website we can load all page data.

Magento 2 has an inbuilt rest API system. So we will use that default API, so then we do not need to create any files for the route URL and for the method.

<?xml version="1.0"?>
<!--
/**
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CMSPage
* Website: http://www.wishusucess.com/
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<!-- Cms Page -->
<route url="/V1/cmsPage/:pageId" method="GET">
<service class="Magento\Cms\Api\PageRepositoryInterface" method="getById"/>
<resources>
<resource ref="Magento_Cms::page"/>
</resources>
</route>
</routes>

So at the end outcome of this article is to make you understand how you can get cms page content using REST API.

 

Step 1: Create Admin Access Token

Magento store verifies your authorization before giving you any response so if you will not authorize your request with an access token then the store will send you an error like you can't access the content because you are not an authorized user.

So, I have created an admin access token by using below admin REST API.

https://wishusucess.com/rest/all/V1/integration/admin/token

Method: POST

Content-Type: JSON

Payload: Admin Details (Admin User and Admin Password)

 

Admin Token Access in Magento 2

Now we have received an admin access token.

We will use that admin access token to authenticate our CMS API request.

So, in order to authenticate our request, we will add that admin token in the header content.

 

Step 2: CMS Page REST API Request

Now, I have sent a request to the Magento store by using the below Magento 2 CMS page API.

https://wishusucess.com/rest/store_id/V1/cmsPage/pageId

So our actual request with getting method looks like below url

https://wishusucess.com/rest/all/V1/cmsPage/2

Method: GET

Payload: None

Header: Authorization

Content-Type: application/JSON

Now with the above details send your CMS Page API request and your Magento store will send you a response with the content of that page.

 

Magento 2 CMS Page REST API

Here in the screenshot, you can see we have received all the details like page identifier, page title, page id, page content, etc.

 

Conclusion:

It's very useful when we get access of our Magento 2 Page content and load on other website without any extra effort of coding or development of Magento CMS API.

 

Related Post:

CMS Block REST API: Get Magento 2 Block Content Using REST API

How To Call Magento 2 REST API For Customer Account Update

 

Recommended Post:

Magento Store: Best 36 Magento Websites Example in The World

CMS Block REST API: Get Magento 2 Block Content Using REST API

This article is all about the cms block page content, Today I will explain how you can get the Magento 2 CMS block content on the third-party server or another website using Magento 2 CMS block REST API.

Magento 2 CMS Block REST API for Get Data

If you will open the following file location in your Magento store then you will get all the list of cms block and cms page rest API.

Magento2_Installed_Directory/vendor/magento/Magento_Cms/etc/webapi.xml

Here you will get file content in something like this, So you just have to use this routing URL in order to get the cms block content data on your other website.

<route url="/V1/cmsBlock/:blockId" method="GET">
<service class="Magento\Cms\Api\BlockRepositoryInterface" method="getById"/>
<resources>
<resource ref="Magento_Cms::block"/>
</resources>
</route>

Now, just follow the step to get your Magento 2 store data content on your other website.

Here, this is the standard URL which we are going to hit, now you can change your block id as per your requirement and stores.

http://www.wishusucess.com/rest/all/V1/cmsBlock/blockId/

Rest: It's a type of API

All: It's a store id of your website

V1: it's a standard way of your route URL

Now the working URL will look something like the below URL.

http://www.wishusucess.com/rest/all/V1/cmsBlock/2

 

Magento 2 Admin Access Token Rest API

First, we have to get the admin access token by using Magento admin token API

https://wishusucess.com/rest/all/V1/integration/admin/token

Now you have to send the body content by using below payload

Payload:

{
"username": "Admin",
"password": "Admin@#123"
}

Method: POST

Now, just press the send button, then you will get the admin access token.

Magento 2 Admin Access Token

In the second step, you have to use the received admin access token in the postman header.

 

CMS Block REST API In Magento 2

Authorization: Bearer kmgupoopitbthwza5dkfm3srjfrtf1tb

content-type: application/json

Now send your request you will get the content of your Magento 2 cms block content of that particular block id.

http://www.wishusucess.com/rest/all/V1/cmsBlock/2

Magento 2 CMS Block REST API

Conclusion:

By using the above method you can get any kind of Magento 2 cms block content based on block id.

 

Related Post:

API Log Checker: How To Check Magento 2 Web API Log Details

Featured Product API: Get Featured Product Using Magento 2 REST API

 

Suggested Post:

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

Featured Product API : Get Featured Product Using Magento 2 REST API

Here, we have created a custom module which is Featured Products API that will help you to get the product collection based on the product attribute.

Featured Product API is a custom module of the Wishusucess Magento developer team, it's an open-source module of wishusucess development team.

So, Let's start the step to create this custom REST API to get the product collection on another website by using the API call.

Featured Products API in Magento 2

 

Steps To Create Featured Products API

app/code/Wishusucess/FeaturProductsApi/registration.php

app/code/Wishusucess/FeaturProductsApi/etc/module.xml

app/code/Wishusucess/FeaturProductsApi/etc/di.xml

app/code/Wishusucess/FeaturProductsApi/etc/webapi.xml

app/code/Wishusucess/FeaturProductsApi/etc/frontend/routes.xml

app/code/Wishusucess/FeaturProductsApi/Model/Api/Custom.php

app/code/Wishusucess/FeaturProductsApi/Controller/Index/Index.php

app/code/Wishusucess/FeaturProductsApi/Api/CustomInterface.php

 

Step 1: Registration FeaturProductsApi

app/code/Wishusucess/FeaturProductsApi/registration.php

<?php
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_FeaturProductsApi
* Website: http://www.wishusucess.com/
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_FeaturProductsApi',
__DIR__
);

 

Step 2: Module Information of FeaturProductsApi

app/code/Wishusucess/FeaturProductsApi/etc/module.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_FeaturProductsApi
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_FeaturProductsApi" setup_version="1.0.0" />
</config>

 

Step 3: Define Dependency Injection

app/code/Wishusucess/FeaturProductsApi/etc/di.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_FeaturProductsApi
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Wishusucess\FeaturProductsApi\Api\CustomInterface" type="Wishusucess\FeaturProductsApi\Model\Api\Custom"/>
</config>

 

Step 4: Create Featured Products API

In this file of Web API, we have to decide the route ID that we have to call in order to get this collection of products on the third-party website or another website.

So, here we have decided the route id which is /V1/wishusucess/featureproducts and the method is GET.

So when we call this method then we have to define this GET method there then only we can get this product collection on that server.

app/code/Wishusucess/FeaturProductsApi/etc/webapi.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_FeaturProductsApi
* Website: http://www.wishusucess.com/
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<route method="GET" url="/V1/wishusucess/featureproducts/">
<service class="Wishusucess\FeaturProductsApi\Api\CustomInterface" method="getPost"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>

 

Step 5: Create Frontend Route File

By using this route.xml file we have decided the route id for the frontend which is featureproducts so this will id we will use in the frontend URL.

app/code/Wishusucess/FeaturProductsApi/etc/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_FeaturProductsApi
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
<route id="featureproducts" frontName="featureproducts">
<module name="Wishusucess_FeaturProductsApi" />
</route>
</router>
</config>

 

Step 6: Featured Products Api Model Class

app/code/Wishusucess/FeaturProductsApi/Model/Api/Custom.php

<?php
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_FeaturProductsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\FeaturProductsApi\Model\Api;

use Psr\Log\LoggerInterface;

class Custom 
{
/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;

public function __construct(
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
array $data = []
) {
$this->resultPageFactory = $resultPageFactory;
$this->_productCollectionFactory = $productCollectionFactory; 
$this->catalogProductVisibility = $catalogProductVisibility;


}

/**
* @inheritdoc
*/

public function getPost()
{
$response = ['success' => false];

try {

$collection = $this->_productCollectionFactory->create();
$collection = $this->_productCollectionFactory->create()->addAttributeToSelect('*')->addAttributeToFilter('status', '1')
->addAttributeToFilter('featured', '1');

$collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());
$result= $collection;
$cart = array();
foreach($result as $value)
{
$cart[] = $value->getData();
}
$response= $cart;
// print_r($cart);


} catch (\Exception $e) {
$response = ['success' => false, 'message' => $e->getMessage()];
}
$returnArray = $response;
return $returnArray; 
}
}

 

Step 7: FeaturProductsApi Controller

This model class collection will filter the product based on the yes-no featured attributes.

So you can create this product attribute in the Magento 2 admin and then add that identifier here.

addAttributeToFilter('featured', '1');

Here featured is a product attribute identifier that will have boolean values yes means 1 and no means 0.

app/code/Wishusucess/FeaturProductsApi/Controller/Index/Index.php

<?php
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_FeaturProductsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\FeaturProductsApi\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action {

/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;

public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
array $data = []
) {
$this->_productCollectionFactory = $productCollectionFactory; 
$this->catalogProductVisibility = $catalogProductVisibility;
parent::__construct(
$context,
$data
);
}

public function execute() {
$collection = $this->_productCollectionFactory->create();
$collection = $this->_productCollectionFactory->create()->addAttributeToSelect('*')->addAttributeToFilter('status', '1')
->addAttributeToFilter('featured', '1');

$collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());
$response = $collection;

echo "<pre>";
// print_r($response->getData());
$cart = array();
foreach($response as $value)
{
$cart[] = $value->getData();
}

print_r($cart);
die();

}

}

 

Step 8:

app/code/Wishusucess/FeaturProductsApi/Api/CustomInterface.php

<?php
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_FeaturProductsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\FeaturProductsApi\Api;

interface CustomInterface
{
/**
* GET for Post api
* @return boolean|array
*/

public function getPost();
}

 

Related Post:

How To Call Magento 2 REST API For Customer Account Update

How To GET Products List Using Magento 2 REST API

 

Download This API

How To Call Magento 2 REST API For Customer Account Update

Here, I am going to explain how you can call Magento 2 Customer REST API to update the customer information from another website. So for the Customer Account Update, we don't need to create any custom API if you don't need any extra facilities.

By using Magento 2 default customer REST API you can create customers from third-party websites and you can use that credentials to get the customer access token and again by using those customer access token you can implement forgot password process.

Magento 2 API Customer Account Update

 

Magento 2 Customer Account Update Default API

There are already default APIs in Magento 2 so simply we are going to use that API and we will create customers and then log in by using that customer API through using a customer access token.

We can also send and receive customer forgot password links on the mail using customer forgot rest API in the Magento store.

 

Magento 2 Create Customer REST API

https://wishusucess.com/rest/all/V1/customers

Method: POST

{
"customer": {
"email": "cs.hemantsingh@gmail.com",
"firstname": "Hemant",
"lastname": "Singh"

},
"password": "cs.hemantsingh@gmail.com"
}

Magento 2 Customer Account Update Create REST API

Now your customer has been created and you will get a response like the below image.

Customer Create Magento 2 REST API

 

Call Customer Login REST API

So here by using the below API you can log in to the Magento 2 store from any other website or third-party website. and you can do customer account update from that server.

This is the default Magento 2 Rest API that is used to call the customer login on another server.

Magento 2 has two steps to login from a third-party website so in the first step, you have to create a customer login token by using your customer details so when you will send a request with the customer login id and password then Magento stores send you the token.

After that, you have to utilize that tokens as authentication and then you will get your personal details.

http://wishusucess.com/rest/all/V1/integration/customer/token

Now you have created a customer account so you have to use that account credentials and send it with the POST method.

{
"username": "cs.hemantsingh@gmail.com",
"password": "Admin@$123456"
}

Magento 2 Customer Account Update Get Login Token

So here you have received your customer token now we will use this customer token for any kind of data receiving from the Magento 2 store.

So here we are using those tokens to log in to our Magento 2 store.

https://wishusucess.com/rest/V1/customers/me

Method: GET

Magento 2 Customer REST API Login Bu Access Token

You can see by using the tokens we have received each and every detail of the customer.

similarly, we can use that tokens to send a forgot password link on our registered email id.

https://wishusucess.com/rest/all/V1/customers/password

Method: PUT

Customer Account Update Authorisation TokenNow here we have added the received tokens from the Magento 2 store, This is the authorization of Magento 2 existing customers.

Magento 2 Customer Forgot Password REST API

Now you can see the forgot password email has been sent by using the Magento 2 REST API, and we have received the response true which means we have received a mail with forgot password link.

Forgot password Link Mail in Magento 2 Customer Account Update

 

Customer Account Update Email Available API

By using Magento 2 default REST API we can check whether customer email is available or not, if the email is available then you will receive a response true something like the below image.

https://wishusucess.com/rest/all/V1/customers/isEmailAvailable

Method: POST

Check Email Avilablity Using Magento 2 REST API

 

Conclusion: Magento 2 provides a default web API for access the data from other websites and we can use that API to retrieve the data or save the data.

 

Related Post:

ContactUs REST API: Create Magento 2 Custom Contact Us REST API

Checkout REST API: Get Checkout Data Using REST API Key in Magento

 

Wishusucess GitHub Profile

 

How To GET Products List Using Magento 2 REST API

To Get products list Through Magento 2 REST API is not a big deal when you develop any native application. Here I am going to explain how we can get all the products list using Magento 2 REST API.

Magento 2 REST API GET Products List

Wishuscess_ProductList is a complete module that helps you to decide a custom web API route id and that route id we will use to call this Wishuscess_ProductList on the postman server to test our custom REST API to get the product list.

 

Magento 2 REST API TO GET Products List

Here we have to create two classes one is the product list interface and the second is the model product list repository which helps us to get the complete product list through API calls.

app/code/Wishusucess/ProductsList/registration.php

app/code/Wishusucess/ProductsList/etc/module.xml

app/code/Wishusucess/ProductsList/etc/di.xml

app/code/Wishusucess/ProductsList/etc/webapi.xml

app/code/Wishusucess/ProductsList/Api/ProductListInterface.php

app/code/Wishusucess/ProductsList/Model/ProductListRepository.php

 

Create Magento 2 Rest API GetProductsList

You have to create a separate module for it so then you can decide the rest web API route id and then that web API you have to call on your different server to get the product list data.

Step 1: Registration

app/code/Wishusucess/ProductsList/registration.php

<?php
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_ProductsList
* Website: http://www.wishusucess.com/
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_ProductsList',
__DIR__
);

 

Step 2: Module Information

app/code/Wishusucess/ProductsList/etc/module.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_Customer
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_ProductsList" setup_version="1.0.0" />
</config>

 

Step 3: Dependency Injection

app/code/Wishusucess/ProductsList/etc/di.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_Customer
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Wishusucess\ProductsList\Api\ProductListInterface" type="Wishusucess\ProductsList\Model\ProductListRepository" />
</config>

 

Step 4: Create Route ID To GET Products List

app/code/Wishusucess/ProductsList/etc/webapi.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_Customer
* Website: http://www.wishusucess.com/
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/wishusucess/products" method="GET">
<service class="Wishusucess\ProductsList\Api\ProductListInterface" method="getList"/>
<resources>
<resource ref="Magento_Catalog::products"/>
</resources>
</route>
</routes>

 

Step 5: Create Model Repository Class

By using this repository class you will decide how you are going to receive or process the request. Suppose you are getting a request to give the product list based on the SKUs then you have to decide all those parameters here.

Here you can set the product links as well in all those products with cache images and we have also added a function to get the product based on the product by id so when you will hit the API with product id then you will get the result.

app/code/Wishusucess/ProductsList/Model/ProductListRepository.php

<?php
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_ProductsList
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\ProductsList\Model;
use Wishusucess\ProductsList\Api\ProductListInterface;

use Magento\Catalog\Api\Data\ProductExtension;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\Product\Gallery\MimeTypeExtensionMap;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Eav\Model\Entity\Attribute\Exception as AttributeException;
use Magento\Framework\Api\Data\ImageContentInterfaceFactory;
use Magento\Framework\Api\ImageContentValidatorInterface;
use Magento\Framework\Api\ImageProcessorInterface;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\DB\Adapter\ConnectionException;
use Magento\Framework\DB\Adapter\DeadlockException;
use Magento\Framework\DB\Adapter\LockWaitException;
use Magento\Framework\EntityManager\Operation\Read\ReadExtensions;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\TemporaryState\CouldNotSaveException as TemporaryCouldNotSaveException;
use Magento\Framework\Exception\ValidatorException;
use Magento\Catalog\Model\Product;

/**
* Product Repository.
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyFields)
*/
class ProductListRepository implements ProductListInterface
{
/**
* @var \Magento\Catalog\Api\ProductCustomOptionRepositoryInterface
*/
protected $optionRepository;

/**
* @var \Magento\Catalog\Model\ProductFactory
*/
protected $productFactory;

/**
* @var Product[]
*/
protected $instances = [];

/**
* @var Product[]
*/
protected $instancesById = [];

/**
* @var \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper
*/
protected $initializationHelper;

/**
* @var \Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory
*/
protected $searchResultsFactory;

/**
* @var \Magento\Framework\Api\SearchCriteriaBuilder
*/
protected $searchCriteriaBuilder;

/**
* @var \Magento\Framework\Api\FilterBuilder
*/
protected $filterBuilder;

/**
* @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
*/
protected $collectionFactory;

/**
* @var \Magento\Catalog\Model\ResourceModel\Product
*/
protected $resourceModel;

/**
* @var Product\Initialization\Helper\ProductLinks
*/
protected $linkInitializer;

/**
* @var Product\LinkTypeProvider
*/
protected $linkTypeProvider;

/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;

/**
* @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface
*/
protected $attributeRepository;

/**
* @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface
*/
protected $metadataService;

/**
* @var \Magento\Framework\Api\ExtensibleDataObjectConverter
*/
protected $extensibleDataObjectConverter;

/**
* @var \Magento\Framework\Filesystem
*/
protected $fileSystem;

/**
* @deprecated
* @see \Magento\Catalog\Model\MediaGalleryProcessor
* @var ImageContentInterfaceFactory
*/
protected $contentFactory;

/**
* @deprecated
* @see \Magento\Catalog\Model\MediaGalleryProcessor
* @var ImageProcessorInterface
*/
protected $imageProcessor;

/**
* @var \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface
*/
protected $extensionAttributesJoinProcessor;

/**
* @var ProductRepository\MediaGalleryProcessor
*/
protected $mediaGalleryProcessor;

/**
* @var CollectionProcessorInterface
*/
private $collectionProcessor;

/**
* @var int
*/
private $cacheLimit = 0;

/**
* @var \Magento\Framework\Serialize\Serializer\Json
*/
private $serializer;

/**
* @var ReadExtensions
*/
private $readExtensions;

/**
* ProductRepository constructor.
* @param \Magento\Catalog\Model\ProductFactory $productFactory
* @param \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $initializationHelper
* @param \Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory $searchResultsFactory
* @param ResourceModel\Product\CollectionFactory $collectionFactory
* @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
* @param \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository
* @param ResourceModel\Product $resourceModel
* @param Product\Initialization\Helper\ProductLinks $linkInitializer
* @param Product\LinkTypeProvider $linkTypeProvider
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\Api\FilterBuilder $filterBuilder
* @param \Magento\Catalog\Api\ProductAttributeRepositoryInterface $metadataServiceInterface
* @param \Magento\Framework\Api\ExtensibleDataObjectConverter $extensibleDataObjectConverter
* @param Product\Option\Converter $optionConverter
* @param \Magento\Framework\Filesystem $fileSystem
* @param ImageContentValidatorInterface $contentValidator
* @param ImageContentInterfaceFactory $contentFactory
* @param MimeTypeExtensionMap $mimeTypeExtensionMap
* @param ImageProcessorInterface $imageProcessor
* @param \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface $extensionAttributesJoinProcessor
* @param CollectionProcessorInterface $collectionProcessor [optional]
* @param \Magento\Framework\Serialize\Serializer\Json|null $serializer
* @param int $cacheLimit [optional]
* @param ReadExtensions|null $readExtensions
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function __construct(
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $initializationHelper,
\Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory $searchResultsFactory,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository,
\Magento\Catalog\Model\ResourceModel\Product $resourceModel,
\Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks $linkInitializer,
\Magento\Catalog\Model\Product\LinkTypeProvider $linkTypeProvider,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\Api\FilterBuilder $filterBuilder,
\Magento\Catalog\Api\ProductAttributeRepositoryInterface $metadataServiceInterface,
\Magento\Framework\Api\ExtensibleDataObjectConverter $extensibleDataObjectConverter,
\Magento\Catalog\Model\Product\Option\Converter $optionConverter,
\Magento\Framework\Filesystem $fileSystem,
ImageContentValidatorInterface $contentValidator,
ImageContentInterfaceFactory $contentFactory,
MimeTypeExtensionMap $mimeTypeExtensionMap,
ImageProcessorInterface $imageProcessor,
\Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface $extensionAttributesJoinProcessor,
CollectionProcessorInterface $collectionProcessor = null,
\Magento\Framework\Serialize\Serializer\Json $serializer = null,
$cacheLimit = 1000,
ReadExtensions $readExtensions = null
) {
$this->productFactory = $productFactory;
$this->collectionFactory = $collectionFactory;
$this->initializationHelper = $initializationHelper;
$this->searchResultsFactory = $searchResultsFactory;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->resourceModel = $resourceModel;
$this->linkInitializer = $linkInitializer;
$this->linkTypeProvider = $linkTypeProvider;
$this->storeManager = $storeManager;
$this->attributeRepository = $attributeRepository;
$this->filterBuilder = $filterBuilder;
$this->metadataService = $metadataServiceInterface;
$this->extensibleDataObjectConverter = $extensibleDataObjectConverter;
$this->fileSystem = $fileSystem;
$this->contentFactory = $contentFactory;
$this->imageProcessor = $imageProcessor;
$this->extensionAttributesJoinProcessor = $extensionAttributesJoinProcessor;
$this->collectionProcessor = $collectionProcessor ?: $this->getCollectionProcessor();
$this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Framework\Serialize\Serializer\Json::class);
$this->cacheLimit = (int)$cacheLimit;
$this->readExtensions = $readExtensions ?: \Magento\Framework\App\ObjectManager::getInstance()
->get(ReadExtensions::class);
}

/**
* @inheritdoc
*/
public function get($sku, $editMode = false, $storeId = null, $forceReload = false)
{
$cacheKey = $this->getCacheKey([$editMode, $storeId]);
$cachedProduct = $this->getProductFromLocalCache($sku, $cacheKey);
if ($cachedProduct === null || $forceReload) {
$productId = $this->resourceModel->getIdBySku($sku);
if (!$productId) {
throw new NoSuchEntityException(__('Requested product doesn\'t exist'));
}

$product = $this->getById($productId, $editMode, $storeId, $forceReload);

$this->cacheProduct($cacheKey, $product);
$cachedProduct = $product;
}

return $cachedProduct;
}

/**
* @inheritdoc
*/
public function getById($productId, $editMode = false, $storeId = null, $forceReload = false)
{
$cacheKey = $this->getCacheKey([$editMode, $storeId]);
if (!isset($this->instancesById[$productId][$cacheKey]) || $forceReload) {
$product = $this->productFactory->create();
if ($editMode) {
$product->setData('_edit_mode', true);
}
if ($storeId !== null) {
$product->setData('store_id', $storeId);
}
$product->load($productId);
if (!$product->getId()) {
throw new NoSuchEntityException(__('Requested product doesn\'t exist'));
}
$this->cacheProduct($cacheKey, $product);
}

return $this->instancesById[$productId][$cacheKey];
}

/**
* Get key for cache
*
* @param array $data
* @return string
*/
protected function getCacheKey($data)
{
$serializeData = [];
foreach ($data as $key => $value) {
if (is_object($value)) {
$serializeData[$key] = $value->getId();
} else {
$serializeData[$key] = $value;
}
}
$serializeData = $this->serializer->serialize($serializeData);

return sha1($serializeData);
}

/**
* Add product to internal cache and truncate cache if it has more than cacheLimit elements.
*
* @param string $cacheKey
* @param ProductInterface $product
* @return void
*/
private function cacheProduct($cacheKey, ProductInterface $product)
{
$_imageHelper = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Catalog\Helper\Image');
$image = $_imageHelper->init($product, 'thumbnail', ['type'=>'thumbnail'])->keepAspectRatio(true)->resize('200','200')->getUrl();
$product->setCustomAttribute('thumbnail', $image);

$this->instancesById[$product->getId()][$cacheKey] = $product;
$this->saveProductInLocalCache($product, $cacheKey);

if ($this->cacheLimit && count($this->instances) > $this->cacheLimit) {
$offset = round($this->cacheLimit / -2);
$this->instancesById = array_slice($this->instancesById, $offset, null, true);
$this->instances = array_slice($this->instances, $offset, null, true);
}
}

/**
* Merge data from DB and updates from request
*
* @param array $productData
* @param bool $createNew
* @return ProductInterface|Product
* @throws NoSuchEntityException
*/
protected function initializeProductData(array $productData, $createNew)
{
unset($productData['media_gallery']);
if ($createNew) {
$product = $this->productFactory->create();
$this->assignProductToWebsites($product);
if (isset($productData['price']) && !isset($productData['product_type'])) {
$product->setTypeId(Product\Type::TYPE_SIMPLE);
}
} else {
if (!empty($productData['id'])) {
unset($this->instancesById[$productData['id']]);
$product = $this->getById($productData['id']);
} else {
$this->removeProductFromLocalCache($productData['sku']);
$product = $this->get($productData['sku']);
}
}

foreach ($productData as $key => $value) {
$product->setData($key, $value);
}

return $product;
}

/**
* Assign product to websites.
*
* @param \Magento\Catalog\Model\Product $product
* @return void
*/
private function assignProductToWebsites(\Magento\Catalog\Model\Product $product)
{
if ($this->storeManager->getStore(true)->getCode() === \Magento\Store\Model\Store::ADMIN_CODE) {
$websiteIds = array_keys($this->storeManager->getWebsites());
} else {
$websiteIds = [$this->storeManager->getStore()->getWebsiteId()];
}

$product->setWebsiteIds($websiteIds);
}

/**
* Process product links, creating new links, updating and deleting existing links
*
* @param ProductInterface $product
* @param \Magento\Catalog\Api\Data\ProductLinkInterface[] $newLinks
* @return $this
* @throws NoSuchEntityException
*/
private function processLinks(ProductInterface $product, $newLinks)
{
if ($newLinks === null) {
// If product links were not specified, don't do anything
return $this;
}

// Clear all existing product links and then set the ones we want
$linkTypes = $this->linkTypeProvider->getLinkTypes();
foreach (array_keys($linkTypes) as $typeName) {
$this->linkInitializer->initializeLinks($product, [$typeName => []]);
}

// Set each linktype info
if (!empty($newLinks)) {
$productLinks = [];
foreach ($newLinks as $link) {
$productLinks[$link->getLinkType()][] = $link;
}

foreach ($productLinks as $type => $linksByType) {
$assignedSkuList = [];
/** @var \Magento\Catalog\Api\Data\ProductLinkInterface $link */
foreach ($linksByType as $link) {
$assignedSkuList[] = $link->getLinkedProductSku();
}
$linkedProductIds = $this->resourceModel->getProductsIdsBySkus($assignedSkuList);

$linksToInitialize = [];
foreach ($linksByType as $link) {
$linkDataArray = $this->extensibleDataObjectConverter
->toNestedArray($link, [], \Magento\Catalog\Api\Data\ProductLinkInterface::class);
$linkedSku = $link->getLinkedProductSku();
if (!isset($linkedProductIds[$linkedSku])) {
throw new NoSuchEntityException(
__('Product with SKU "%1" does not exist', $linkedSku)
);
}
$linkDataArray['product_id'] = $linkedProductIds[$linkedSku];
$linksToInitialize[$linkedProductIds[$linkedSku]] = $linkDataArray;
}

$this->linkInitializer->initializeLinks($product, [$type => $linksToInitialize]);
}
}

$product->setProductLinks($newLinks);

return $this;
}

/**
* @inheritdoc
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function save(ProductInterface $product, $saveOptions = false)
{
$tierPrices = $product->getData('tier_price');

try {
$existingProduct = $product->getId() ? $this->getById($product->getId()) : $this->get($product->getSku());

$product->setData(
$this->resourceModel->getLinkField(),
$existingProduct->getData($this->resourceModel->getLinkField())
);
if (!$product->hasData(Product::STATUS)) {
$product->setStatus($existingProduct->getStatus());
}

/** @var ProductExtension $extensionAttributes */
$extensionAttributes = $product->getExtensionAttributes();
if (empty($extensionAttributes->__toArray())) {
$product->setExtensionAttributes($existingProduct->getExtensionAttributes());
}
} catch (NoSuchEntityException $e) {
$existingProduct = null;
}

$productDataArray = $this->extensibleDataObjectConverter
->toNestedArray($product, [], ProductInterface::class);
$productDataArray = array_replace($productDataArray, $product->getData());
$ignoreLinksFlag = $product->getData('ignore_links_flag');
$productLinks = null;
if (!$ignoreLinksFlag && $ignoreLinksFlag !== null) {
$productLinks = $product->getProductLinks();
}
if (!isset($productDataArray['store_id'])) {
$productDataArray['store_id'] = (int)$this->storeManager->getStore()->getId();
}
$product = $this->initializeProductData($productDataArray, empty($existingProduct));

$this->processLinks($product, $productLinks);
if (isset($productDataArray['media_gallery_entries'])) {
$this->getMediaGalleryProcessor()->processMediaGallery(
$product,
$productDataArray['media_gallery_entries']
);
}

if (!$product->getOptionsReadonly()) {
$product->setCanSaveCustomOptions(true);
}

$validationResult = $this->resourceModel->validate($product);
if (true !== $validationResult) {
throw new \Magento\Framework\Exception\CouldNotSaveException(
__('Invalid product data: %1', implode(',', $validationResult))
);
}

if ($tierPrices !== null) {
$product->setData('tier_price', $tierPrices);
}

$this->saveProduct($product);
$this->removeProductFromLocalCache($product->getSku());
unset($this->instancesById[$product->getId()]);

return $this->get($product->getSku(), false, $product->getStoreId());
}

/**
* @inheritdoc
*/
public function delete(ProductInterface $product)
{
$sku = $product->getSku();
$productId = $product->getId();
try {
$this->removeProductFromLocalCache($product->getSku());
unset($this->instancesById[$product->getId()]);
$this->resourceModel->delete($product);
} catch (ValidatorException $e) {
throw new CouldNotSaveException(__($e->getMessage()));
} catch (\Exception $e) {
throw new \Magento\Framework\Exception\StateException(
__('Unable to remove product %1', $sku)
);
}
$this->removeProductFromLocalCache($sku);
unset($this->instancesById[$productId]);

return true;
}

/**
* @inheritdoc
*/
public function deleteById($sku)
{
$product = $this->get($sku);

return $this->delete($product);
}

/**
* @inheritdoc
*/
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria)
{
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
$collection = $this->collectionFactory->create();
$this->extensionAttributesJoinProcessor->process($collection);

$collection->addAttributeToSelect('*');
$collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
$collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');
$collection->addMinimalPrice();//adding minmalprice you can change to addFinalPrice amjad fluxstore

$this->collectionProcessor->process($searchCriteria, $collection);

$collection->load();

$collection->addCategoryIds();
$this->addExtensionAttributes($collection);
$searchResult = $this->searchResultsFactory->create();
$searchResult->setSearchCriteria($searchCriteria);
$searchResult->setItems($collection->getItems());
$searchResult->setTotalCount($collection->getSize());

foreach ($collection->getItems() as $product) {
$this->cacheProduct(
$this->getCacheKey(
[
false,
$product->getStoreId()
]
),
$product
);
}

return $searchResult;
}

/**
* Add extension attributes to loaded items.
*
* @param Collection $collection
* @return Collection
*/
private function addExtensionAttributes(Collection $collection): Collection
{
foreach ($collection->getItems() as $item) {
$this->readExtensions->execute($item);
}

return $collection;
}

/**
* Helper function that adds a FilterGroup to the collection.
*
* @deprecated 101.1.0
* @param \Magento\Framework\Api\Search\FilterGroup $filterGroup
* @param Collection $collection
* @return void
*/
protected function addFilterGroupToCollection(
\Magento\Framework\Api\Search\FilterGroup $filterGroup,
Collection $collection
) {
$fields = [];
$categoryFilter = [];
foreach ($filterGroup->getFilters() as $filter) {
$conditionType = $filter->getConditionType() ?: 'eq';

if ($filter->getField() == 'category_id') {
$categoryFilter[$conditionType][] = $filter->getValue();
continue;
}
$fields[] = ['attribute' => $filter->getField(), $conditionType => $filter->getValue()];
}

if ($categoryFilter) {
$collection->addCategoriesFilter($categoryFilter);
}

if ($fields) {
$collection->addFieldToFilter($fields);
}
}

/**
* Clean internal product cache
*
* @return void
*/
public function cleanCache()
{
$this->instances = null;
$this->instancesById = null;
}

/**
* Retrieve media gallery processor.
*
* @return ProductRepository\MediaGalleryProcessor
*/
private function getMediaGalleryProcessor()
{
if (null === $this->mediaGalleryProcessor) {
$this->mediaGalleryProcessor = \Magento\Framework\App\ObjectManager::getInstance()
->get(ProductRepository\MediaGalleryProcessor::class);
}

return $this->mediaGalleryProcessor;
}

/**
* Retrieve collection processor
*
* @deprecated 101.1.0
* @return CollectionProcessorInterface
*/
private function getCollectionProcessor()
{
if (!$this->collectionProcessor) {
$this->collectionProcessor = \Magento\Framework\App\ObjectManager::getInstance()->get(
'Magento\Catalog\Model\Api\SearchCriteria\ProductCollectionProcessor'
);
}

return $this->collectionProcessor;
}

/**
* Gets product from the local cache by SKU.
*
* @param string $sku
* @param string $cacheKey
* @return Product|null
*/
private function getProductFromLocalCache(string $sku, string $cacheKey)
{
$preparedSku = $this->prepareSku($sku);
if (!isset($this->instances[$preparedSku])) {
return null;
}

return $this->instances[$preparedSku][$cacheKey] ?? null;
}

/**
* Removes product in the local cache.
*
* @param string $sku
* @return void
*/
private function removeProductFromLocalCache(string $sku)
{
$preparedSku = $this->prepareSku($sku);
unset($this->instances[$preparedSku]);
}

/**
* Saves product in the local cache.
*
* @param Product $product
* @param string $cacheKey
*/
private function saveProductInLocalCache(Product $product, string $cacheKey)
{
$preparedSku = $this->prepareSku($product->getSku());
$this->instances[$preparedSku][$cacheKey] = $product;
}

/**
* Converts SKU to lower case and trims.
*
* @param string $sku
* @return string
*/
private function prepareSku(string $sku): string
{
return mb_strtolower(trim($sku));
}

/**
* Save product resource model.
*
* @param ProductInterface|Product $product
* @throws TemporaryCouldNotSaveException
* @throws InputException
* @throws CouldNotSaveException
* @throws LocalizedException
*/
private function saveProduct($product)
{
try {
$this->removeProductFromLocalCache($product->getSku());
unset($this->instancesById[$product->getId()]);
$this->resourceModel->save($product);
} catch (ConnectionException $exception) {
throw new TemporaryCouldNotSaveException(
__('Database connection error'),
$exception,
$exception->getCode()
);
} catch (DeadlockException $exception) {
throw new TemporaryCouldNotSaveException(
__('Database deadlock found when trying to get lock'),
$exception,
$exception->getCode()
);
} catch (LockWaitException $exception) {
throw new TemporaryCouldNotSaveException(
__('Database lock wait timeout exceeded'),
$exception,
$exception->getCode()
);
} catch (AttributeException $exception) {
throw InputException::invalidFieldValue(
$exception->getAttributeCode(),
$product->getData($exception->getAttributeCode()),
$exception
);
} catch (ValidatorException $e) {
throw new CouldNotSaveException(__($e->getMessage()));
} catch (LocalizedException $e) {
throw $e;
} catch (\Exception $e) {
throw new CouldNotSaveException(__('Unable to save product'), $e);
}
}
}

 

Step 6: API Class GET Products List Interface

So, here you have to create a function getList() that will have some search criteria as a parameter and when you will give that parameter and then send a request then Magento 2 will ask you to authorize first so you have to send with an admin token then Magento 2 website will give you the products list.

app/code/Wishusucess/ProductsList/Api/ProductListInterface.php

<?php
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_Customer
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\ProductsList\Api;
/**
* @api
*/
interface ProductListInterface
{
/**
* Get product list
*
* @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
* @return \Magento\Catalog\Api\Data\ProductSearchResultsInterface
*/
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);
}

 

Now, Run The Following command:

php bin/magento s:up

php bin/magento s:s:d -f

php bin/magento c:c

Now, we have created our Magento 2 product list rest API, so in order to use this API we have to create an admin token first then we have to use that token and send the request in the below format.

https://www.wishusucess.com/rest/store_id/V1/wishusucess/products

With Get method when you will send the request in above format of URL then you will get the product list data.

Download ProductsList API

 

Recommended Post:

Magento 2 Customer API: Create Custom API For Customer

ContactUs REST API: Create Magento 2 Custom Contact Us REST API

 

How To Get Product Image URL Using REST API in Magento 2

In this Magento 2 API article, I am going to explain to you how we can get the data of Magento 2 product image URL using REST API or if I will explain in simple terms then I can say how to get data from Magento 2 RESt API.

Magento 2 REST API For GET URL

So when you are developing a native mobile application then that time you need to get the ProductImageURL from the product collection of Magento 2 using REST API.

It's needed when you need the product images URLs from your current product when you develop your application in Magento but you are using something other technology for the frontend like ReactJS, NodeJS, etc.

So it's doesn't matter why and where you are using you can easily get the product URLs from with the image on your frontend using Magento 2 REST API for product URL.

So here you have to decide your REST API route URL and by using that path you can easily hit the URL and get the data.

 

Get Product Image URL Custom API Module

So in order to develop this module, you have to create some basic files and as we all know most of the basic files here like: module.xml, di.xml but webapi.xml is the new file for this module.

So we will understand step-by-step custom module creation for getting ProductImageURL using REST API in Magento 2.

app/code/Wishusucess/ProductImagesUrl/registration.php

app/code/Wishusucess/ProductImagesUrl/etc/module.xml

app/code/Wishusucess/ProductImagesUrl/etc/di.xml

app/code/Wishusucess/ProductImagesUrl/etc/webapi.xml

app/code/Wishusucess/ProductImagesUrl/Model/GetProductImageUrl.php

app/code/Wishusucess/ProductImagesUrl/Api/GetProductImage.php

 

Step 1:

You have to register your module first by using the below registration.php file

app/code/Wishusucess/ProductImagesUrl/registration.php

<?php
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_ProductImagesUrl Get ProductImageURL Using REST API
* Website: http://www.wishusucess.com/
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_ProductImagesUrl',
__DIR__
);

 

Step 2:

Give your module basic information by using the below module.xml file

app/code/Wishusucess/ProductImagesUrl/etc/module.xml

<?xml version="1.0"?>
<!--
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_ProductImagesUrl Get ProductImageURL Using REST API
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_ProductImagesUrl" >
</module>
</config>

 

Step 3:

Now decide the preferences of your custom module by using below di.xml file

app/code/Wishusucess/ProductImagesUrl/etc/di.xml

<?xml version="1.0"?>
<!--
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_ProductImagesUrl Get ProductImageURL Using REST API
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<preference for="Wishusucess\ProductImagesUrl\Api\GetProductImage" type="Wishusucess\ProductImagesUrl\Model\GetProductImageUrl" />
</config>

 

Step 4: Routing - Get Image URL By API

Here, you can decide the route path of your REST API by using the webapi.xml file and this file also consists of the method which you're applying over the API, so when you will use this API after complete development then you have to use this method there to get the product image urls.

app/code/Wishusucess/ProductImagesUrl/etc/webapi.xml

<?xml version="1.0"?>
<!--
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_ProductImagesUrl Get ProductImageURL Using REST API
* Website: http://www.wishusucess.com/
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<route url="/V1/getproductimage/:sku" method="GET">
<service class="Wishusucess\ProductImagesUrl\Api\GetProductImage" method="getProductImageUrl" />
<resources>
<resource ref="anonymous" />
</resources>
</route>
</routes>

 

Step 5: Model Class To Get Product Image Rest API

This class will decide how you want to retrieve the product URL data on the frontend so here you have to implement a class like GetProductImageUrl which implements GetProductImage.

app/code/Wishusucess/ProductImagesUrl/Model/GetProductImageUrl.php

<?php
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_ProductImagesUrl Get ProductImageURL Using REST API
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\ProductImagesUrl\Model;

use Wishusucess\ProductImagesUrl\Api\GetProductImage;

class GetProductImageUrl implements GetProductImage
{
/**
* @var \Magento\Store\Model\App\Emulation
*/
protected $appEmulation;

/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;

/**
* @var \Magento\Catalog\Api\ProductRepositoryInterface
*/
protected $productRepository;

/**
* @var \Magento\Catalog\Helper\Image
*/
protected $imageHelper;

/**
* @param \Magento\Store\Model\App\Emulation $appEmulation
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
* @param \Magento\Catalog\Helper\Image $imageHelper
*/
public function __construct(
\Magento\Store\Model\App\Emulation $appEmulation,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Catalog\Helper\Image $imageHelper
) {
$this->appEmulation = $appEmulation;
$this->storeManager = $storeManager;
$this->productRepository = $productRepository;
$this->imageHelper = $imageHelper;
}

public function getProductImageUrl($sku)
{
$storeId = $this->storeManager->getStore()->getId();
$product = $this->productRepository->get($sku);

$this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);
if (!$product)
{
$response = [
[
"code" => '301',
"message" => "SKU " . $productSku . " Not Found On Magento",
],
];
return $response;
}
else
{
$image_url = $this->imageHelper->init($product, 'product_base_image')->getUrl();
$response = [
[
"product_image_url" => $image_url,
],
];
return $response;
}

$this->appEmulation->stopEnvironmentEmulation();
}
}

 

Step 6: Create REST API Class For Product Image URL

Now here we are using a function which is getProductImageUrl($sku) that will be processed over the SKU data.

app/code/Wishusucess/ProductImagesUrl/Api/GetProductImage.php

<?php
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_ProductImagesUrl Get ProductImageURL Using REST API
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\ProductImagesUrl\Api;

interface GetProductImage
{
/**
* @api
* @param string $sku
* @return array
*/
public function getProductImageUrl($sku);
}

 

Now, we run the following command:

php bin/magento s:up

php bin/magento s:s:d -f

php bin/magento c:c

Now you can check the result by using the postman, so here I am showing you the postman screenshot of how it's showing the data.

Get Product Image URL REST API

 

Related Post:

How To Get Category List By REST API and GraphQL In Magento 2, E.g.

Sign Up Rest API: How to Call Magento 2 Customer Sign Up Rest API, E.g.

Magento 2 Customer API: Create Custom API For Customer

 

Magento 2 Get Product Image URL REST API

Download API

 

How To Get Category List By REST API and GraphQL In Magento 2, E.g.

In this article, I will explain how you can Get Categories List By REST API in Magento 2 default categories REST API, and also we will get the same data in Magento 2 GraphQL.  It's basically used nowadays in native application development using Magento 2.

When we develop an e-commerce mobile application in android or ReactJS using Magento 2 shopping framework then usually we get categories data and other data of the Magento store using REST API or GraphQL.

Therefore, here I will explain how we can get the categories data using Magento 2 REST API and GraphQL.

We will use two tools to get the data from Magento 2 store.

  • Postman for REST API
  • Altair for GraphQL

 

Get Categories List By REST API

In Magento 2 whenever we try to get some data then we need to create the token first then that token we have to send with the request so Magento 2 store will verify the tokens and validate that request.

So here we are trying to get all categories data so we have to get the admin token first by using admin user.

Endpoint:

https://wishusucess.com/rest/all/V1/integration/admin/token

Note: In the above endpoint, you have to replace the domain wishusucess.com with your domain name.

Now Send Request by using the below syntax in JSON format:

{

"username": "Admin",

"password": "Admin@77#123"

}

so if everything will be correct then you will get the response below format.

So here we have received an admin access token by using an admin user.

Create Admin Token Using REST API

Now we will use this admin token for authorization and get the categories data so we have to send the token with the request so that token will be validated by the Magento 2 store and if the token will get validated then you will get the response something like below format.

Get Categories List By REST API and GraphQL

So, in the above image, you can see that the admin access token has been validated and the server sent the details of all the categories list.

Endpoint:

https://wishusucess.com/rest/V1/categories

Get Categories List By REST API

In case of any token invalidation, the server will respond to you like you are not a valid user and you can't access the resources.

Invalid Access Token Message

 

Get Categories List By GraphQL in Magento 2

In order to get the categories list using Magento 2 Graphql, we have to send the request in query format and then we have to specify the Graphql API in the URL section.

So here I have defined a root category in the query which is a default category in my store so all the subcategories of that particular id will show in the result.

https://wishusucess.com/graphql

Now I have submitted the query with the following details in the request then I received a response like the below image.

{
category(id: 2) {
products {
total_count
page_info {
current_page
page_size
}
}
children_count
children {
id
level
name
path
children {
id
level
name
path
children {
id
level
name
path
children {
id
level
name
path
}
}
}
}
}
}

This is the response to the Magento 2 Category list data query in Magento 2 using the Altair Graphql tool.

Magento 2 Get Categories List by GraphQL

 

Related Post:

Sign Up Rest API: How to Call Magento 2 Customer Sign Up Rest API, E.g.

Magento 2 Customer API: Create Custom API For Customer

 

Recommended Post:

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

SEO Packages: How Much Do SEO Packages Cost in India, SEO Pricing