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

 

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

In this article on the Magento 2 Rest API category, I am going to explain how you can sign up Magento 2 new customers from a different website or your localhost system using Magento 2 Customer Sign Up Rest API. So simply we can say call Magento 2 customer sign up reset API Step by step guide from beginning to end.

 

Magento Customers can Purchases in Three Ways:

So basically Magento customer has three choices when they purchase the product from the store.

  • If customers are already registered then they can simply log in and purchase.
  • There are other facilities that don't want to register but want to purchase the product so they can continue as a guest customer.
  • Another option is when customers reached the checkout page then they have to fill in the details and simultaneously can choose to register their account with the store.

So here we will understand the first type of customer and how we can call the Magento default REST API to create a customer.

 

Call Customer Sign Up REST API

By using Magento 2 default REST API we can easily create the customer so in order to create the new customer, we have to call the rest API and check on the postman if the request will send successfully then the account will create and show some response message.

First, we need to open the postman.

Endpoint:

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

Note: wishusucess.com is your domain name if you are using localhost then you have to use your localhost address something like:

http://localhost/magento_installation_directory/rest/all/V1/customers

Method: POST

Request:

{

"customer": {

"email": "cs.hemantsingh@gmail.com",

"firstname": "Hemant",

"lastname": "Singh"

},

"password": "Abcd@$123456"

}

Once you have entered the details then you have to send the request then you will get the result something like an image.

Magento 2 Sign Up REST API

Remember we always send the request in JSON format. so you have to select the format of the request before the request is sent.

Response:

{

"id": 12919,

"group_id": 1,

"created_at": "2021-10-06 19:01:40",

"updated_at": "2021-10-06 19:01:40",

"created_in": "Wishusucess",

"email": "cs.hemantsingh@gmail.com",

"firstname": "Hemant",

"lastname": "Singh",

"store_id": 1,

"website_id": 1,

"addresses": [],

"disable_auto_group_change": 0,

"extension_attributes": {

"is_subscribed": false

}

}

If the email data is already there with the same details of the email then you will get a message like the below image.

Email Already Registered

 

 

Magento 2 create New Customer Using GraphQL

When we talk about GraphQL then there are two things one is mutation and the second is Query so here we are sending a request to create a customer so we will use mutation.

Create Customer Mutation creates a new customer.

Syntax

mutation: {createCustomer(input: CustomerInput!) {CustomerOutput}}

Example usage

You can use the below mutation to create a new customer.

mutation {
createCustomer(
input: {
firstname: "Hemant"
lastname: "Singh"
email: "hemant.singh@wishudeal.com"
password: "Abcd@$123456"
is_subscribed: true
}
) {
customer {
firstname
lastname
email
is_subscribed
}
}
}

 

Create Customer in GraphQL Magento 2

So by using Magento 2 GraphQL you can easily create a new customer and for that, you have to use the endpoint below like that:

https://wishusucess.com/graphql

Here, you can choose your website URL and then type graphql

 

Related Post:

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

 

Magento 2 Customer API: Create Custom API For Customer

Wishusucess Magento 2 Customer API helps Magento developers to generate an Application Programming Interface for their own use.

Magento 2 Customer API Address

By adding this customer API you will be able to change customer email, change the password by customer id and send the notification on mail after changing the further data.

Also, Magento customers can change address delete the address, and save the new address from other websites or servers using this Customer application programmable iinterface.

This Customer API is a set of routines, protocols, and other tools which helps developer to get and post the data from other application. Using this API also help application developer to initiate the program to perform the action from other websites successfully.

Wishuscess Magento Development has successfully developed a module to customize the Magento 2 customer.

 

Magento 2 Customer API Module Customization

In order to develop a custom customer API in Magento, we have to create a module and that module needs to create some files.

We need to create some model classes for Account Management and Resource Model for Address Repository which will help you to manage the customer address field.

app/code/Wishusucess/Customer/registration.php

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

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

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

app/code/Wishusucess/Customer/Model/AccountManagement.php

app/code/Wishusucess/Customer/Model/ResourceModel/AddressRepository.php

app/code/Wishusucess/Customer/Api/AccountManagementInterface.php

app/code/Wishusucess/Customer/Api/AddressRepositoryInterface.php

 

Register Wishuscess Customer API

app/code/Wishusucess/Customer/registration.php

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

 

Create Wishuscess Module XML

app/code/Wishusucess/Customer/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_Customer" setup_version="1.0.0">
<sequence>
<module name="Wishusucess_Customer" />
</sequence>
</module>
</config>

 

Define Dependency Injection

app/code/Wishusucess/Customer/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\Customer\Api\AddressRepositoryInterface" type="Wishusucess\Customer\Model\ResourceModel\AddressRepository"/>
<preference for="Wishusucess\Customer\Api\AccountManagementInterface" type="Wishusucess\Customer\Model\AccountManagement"/>
<virtualType name="Wishusucess\Customer\Model\Api\Address\SearchCriteria\CollectionProcessor\CustomerSortingProcessor" type="Magento\Framework\Api\SearchCriteria\CollectionProcessor\SortingProcessor">
<arguments>
<argument name="fieldMapping" xsi:type="array">
<item name="id" xsi:type="string">entity_id</item>
</argument>
<argument name="defaultOrders" xsi:type="array">
<item name="id" xsi:type="string">DESC</item>
</argument>
</arguments>
</virtualType>
<virtualType name="Wishusucess\Customer\Model\Api\Address\SearchCriteria\CustomerCollectionProcessor" type="Magento\Eav\Model\Api\SearchCriteria\CollectionProcessor">
<arguments>
<argument name="processors" xsi:type="array">
<item name="sorting" xsi:type="object">Wishusucess\Customer\Model\Api\Address\SearchCriteria\CollectionProcessor\CustomerSortingProcessor</item>
</argument>
</arguments>
</virtualType>
<type name="Wishusucess\Customer\Model\ResourceModel\AddressRepository">
<arguments>
<argument name="collectionProcessor" xsi:type="object">Wishusucess\Customer\Model\Api\Address\SearchCriteria\CustomerCollectionProcessor</argument>
</arguments>
</type>
</config>

 

Create Magento 2 Customer Web API

This file basically decides the route URL of your API, so here we have created route id is /V1/wishusucess/customers/me/address and this API using put method.

app/code/Wishusucess/Customer/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/customers/me/address" method="PUT">
<service class="Wishusucess\Customer\Api\AddressRepositoryInterface" method="save"/>
<resources>
<resource ref="self"/>
</resources>
<data>
<parameter name="customerId" force="true">%customer_id%</parameter>
</data>
</route>
<route url="/V1/wishusucess/customers/me/address/:addressId" method="DELETE">
<service class="Wishusucess\Customer\Api\AddressRepositoryInterface" method="deleteById"/>
<resources>
<resource ref="self"/>
</resources>
<data>
<parameter name="customerId" force="true">%customer_id%</parameter>
</data>
</route>
<route url="/V1/wishusucess/customers/me/address/:addressId" method="GET">
<service class="Wishusucess\Customer\Api\AddressRepositoryInterface" method="getById"/>
<resources>
<resource ref="self"/>
</resources>
<data>
<parameter name="customerId" force="true">%customer_id%</parameter>
</data>
</route>
<route url="/V1/wishusucess/customers/me/address/search" method="GET">
<service class="Wishusucess\Customer\Api\AddressRepositoryInterface" method="getList"/>
<resources>
<resource ref="self"/>
</resources>
<data>
<parameter name="customerId" force="true">%customer_id%</parameter>
</data>
</route>
<route url="/V1/wishusucess/customers/me/changeEmail" method="POST">
<service class="Wishusucess\Customer\Api\AccountManagementInterface" method="changeEmail"/>
<resources>
<resource ref="self"/>
</resources>
<data>
<parameter name="customerId" force="true">%customer_id%</parameter>
</data>
</route>
<route url="/V1/wishusucess/customers/me/changePassword" method="POST">
<service class="Wishusucess\Customer\Api\AccountManagementInterface" method="changePasswordById"/>
<resources>
<resource ref="self"/>
</resources>
<data>
<parameter name="customerId" force="true">%customer_id%</parameter>
</data>
</route>
</routes>

 

Create Model Account Management For API

Here, you have to decide what action you are going to perform so here we have created a method to change the email and change password by ID and then send email notification mail to the customer.

app/code/Wishusucess/Customer/Model/AccountManagement.php

<?php 
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_Customer
* Website: http://www.wishusucess.com/
*/
declare(strict_types=1);

namespace Wishusucess\Customer\Model;

use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Model\AuthenticationInterface;
use Magento\Customer\Model\EmailNotificationInterface;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Wishusucess\Customer\Api\AccountManagementInterface;

class AccountManagement implements AccountManagementInterface
{
/**
* @var AuthenticationInterface
*/
private $authentication;

/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;

/**
* @var EmailNotificationInterface
*/
private $emailNotification;

/**
* @var \Magento\Customer\Api\AccountManagementInterface
*/
private $accountManagement;

/**
* @param AuthenticationInterface $authentication
* @param CustomerRepositoryInterface $customerRepository
* @param \Magento\Customer\Api\AccountManagementInterface $accountManagement
* @param EmailNotificationInterface $emailNotification
*/
public function __construct(
AuthenticationInterface $authentication,
CustomerRepositoryInterface $customerRepository,
\Magento\Customer\Api\AccountManagementInterface $accountManagement,
EmailNotificationInterface $emailNotification
) {
$this->authentication = $authentication;
$this->customerRepository = $customerRepository;
$this->emailNotification = $emailNotification;
$this->accountManagement = $accountManagement;
}

/**
* @inheritDoc
*/
public function changeEmail($customerId, $newEmail, $currentPassword)
{
$this->authentication->authenticate($customerId, $currentPassword);
$customer = $this->customerRepository->getById($customerId);
$origEmail = $customer->getEmail();
if ($origEmail == $newEmail) {
throw new LocalizedException(__('Cannot change the same email.'));
}
$customer->setEmail($newEmail);
$savedCustomer = $this->customerRepository->save($customer);
//Sending notify email to customer
$this->sendEmailNotification($savedCustomer, $origEmail);
return true;
}

/**
* @inheritDoc
*/
public function changePasswordById($customerId, $currentPassword, $newPassword, $confirmPassword)
{
$customer = $this->customerRepository->getById($customerId);
if ($newPassword != $confirmPassword) {
throw new InputException(__('Password confirmation doesn\'t match entered password.'));
}
$this->accountManagement->changePasswordById($customerId, $currentPassword, $newPassword);
//Sending notify email to customer
$this->sendEmailNotification($customer, $customer->getEmail(), true);
return true;
}

/**
* @param $savedCustomer
* @param $origCustomerEmail
* @param bool $isPasswordChanged
*/
private function sendEmailNotification($savedCustomer, $origCustomerEmail, $isPasswordChanged = false)
{
$this->emailNotification->credentialsChanged(
$savedCustomer,
$origCustomerEmail,
$isPasswordChanged
);
}
}

 

Resource Model Class for Address Repository

Now, this resource model class will allow you to add the address edit the address, and delete the address using this Magento 2 customer application programmable interface from another websites.

app/code/Wishusucess/Customer/Model/ResourceModel/AddressRepository.php

<?php
/**
*
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_Customer
* Website: http://www.wishusucess.com/
*/
declare(strict_types=1);

namespace Wishusucess\Customer\Model\ResourceModel;

use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\AddressSearchResultsInterfaceFactory;
use Magento\Customer\Model\AddressRegistry;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Model\ResourceModel\Address;
use Magento\Customer\Model\ResourceModel\Address\Collection;
use Magento\Customer\Model\ResourceModel\Address\CollectionFactory;
use Magento\Customer\Model\ResourceModel\AddressRepository as MageAddressRepository;
use Magento\Customer\Model\ResourceModel\CustomerRepository;
use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\StateException;
use Wishusucess\Customer\Api\AddressRepositoryInterface;

class AddressRepository implements AddressRepositoryInterface
{
/**
* @var CustomerRepository
*/
private $customerRepository;

/**
* @var MageAddressRepository
*/
private $mageAddressRepository;

/**
* @var AddressRegistry
*/
private $addressRegistry;

/**
* @var CustomerRegistry
*/
private $customerRegistry;

/**
* @var Address
*/
private $addressResourceModel;

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

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

/**
* @var CollectionFactory
*/
private $addressCollectionFactory;

/**
* @var JoinProcessorInterface
*/
private $extensionAttributesJoinProcessor;

/**
* AddressRepository constructor.
* @param CustomerRepository $customerRepository
* @param MageAddressRepository $mageAddressRepository
* @param AddressRegistry $addressRegistry
* @param CustomerRegistry $customerRegistry
* @param Address $addressResourceModel
* @param AddressSearchResultsInterfaceFactory $searchResultsFactory
* @param CollectionProcessorInterface $collectionProcessor
* @param CollectionFactory $addressCollectionFactory
* @param JoinProcessorInterface $extensionAttributesJoinProcessor
*/
public function __construct(
CustomerRepository $customerRepository,
MageAddressRepository $mageAddressRepository,
AddressRegistry $addressRegistry,
CustomerRegistry $customerRegistry,
Address $addressResourceModel,
AddressSearchResultsInterfaceFactory $searchResultsFactory,
CollectionProcessorInterface $collectionProcessor,
CollectionFactory $addressCollectionFactory,
JoinProcessorInterface $extensionAttributesJoinProcessor
) {
$this->customerRepository = $customerRepository;
$this->mageAddressRepository = $mageAddressRepository;
$this->addressRegistry = $addressRegistry;
$this->customerRegistry = $customerRegistry;
$this->addressResourceModel = $addressResourceModel;
$this->searchResultsFactory = $searchResultsFactory;
$this->collectionProcessor = $collectionProcessor;
$this->addressCollectionFactory = $addressCollectionFactory;
$this->extensionAttributesJoinProcessor = $extensionAttributesJoinProcessor;
}

/**
* @inheritDoc
*/
public function save($customerId, $address)
{
if ($address->getId()) {
if (!in_array($address->getId(), $this->getAddressCollectionByCustomerId($customerId)->getAllIds())) {
throw new NoSuchEntityException(__('The address does not belong to the current customer.'));
}
}

$address->setCustomerId($customerId)->setRegion($address->getRegion());
$this->validateData($address);

try {
$this->mageAddressRepository->save($address);
} catch (LocalizedException $e) {
throw new LocalizedException(__('Cannot save address.'));
}

return $address;
}

/**
* @inheritDoc
*/
public function deleteById($customerId, $addressId)
{
$addressCollection = $this->getAddressCollectionByCustomerId($customerId);

if (in_array($addressId, $addressCollection->getAllIds())) {
$address = $this->addressRegistry->retrieve($addressId);

try {
$addressCollection->removeItemByKey($addressId);
$this->addressResourceModel->delete($address);
$this->addressRegistry->remove($addressId);
return true;
} catch (\Exception $e) {
throw new StateException(__('Cannot remove the address.'));
}
} else {
throw new NoSuchEntityException(__('The address does not belong to the current customer.'));
}
}

/**
* @inheritDoc
*/
public function getById($customerId, $addressId)
{
if (in_array($addressId, $this->getAddressCollectionByCustomerId($customerId)->getAllIds())) {
$address = $this->addressRegistry->retrieve($addressId);
return $address->getDataModel();
} else {
throw new NoSuchEntityException(__('The address does not belong to the current customer.'));
}
}

/**
* @inheritDoc
*/
public function getList($customerId, \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria)
{
$searchResults = $this->searchResultsFactory->create();
$customerModel = $this->customerRegistry->retrieve($customerId);
$searchResults->setSearchCriteria($searchCriteria);
/** @var Collection $collection */
$collection = $this->addressCollectionFactory->create()->setCustomerFilter($customerModel);
$this->extensionAttributesJoinProcessor->process($collection, AddressInterface::class);
$this->collectionProcessor->process($searchCriteria, $collection);
$searchResults->setTotalCount($collection->getSize());
$addresses = [];
/** @var \Magento\Customer\Model\Address $addressModel */
foreach ($collection as $addressModel) {
$addresses[] = $addressModel->getDataModel();
}
$searchResults->setItems($addresses);
return $searchResults;
}

/**
* @param int $customerId
* @return Collection
* @throws NoSuchEntityException
*/
private function getAddressCollectionByCustomerId($customerId)
{
$customerModel = $this->customerRegistry->retrieve($customerId);
return $customerModel->getAddressesCollection();
}

/**
* @param AddressInterface $address
* @throws InputException
*/
private function validateData(AddressInterface $address)
{
if (empty($address->getFirstname())) {
$this->throwException(__('Please enter the first name.'));
}
if (empty($address->getLastname())) {
$this->throwException(__('Please enter the last name.'));
}
if (empty($address->getStreet())) {
$this->throwException(__('Please enter the street.'));
}
if (empty($address->getCity())) {
$this->throwException(__('Please enter the city.'));
}

if (empty($address->getTelephone())) {
$this->throwException(__('Please enter the phone number.'));
}

$countryId = $address->getCountryId();

if (empty($address->getPostcode())) {
$this->throwException(__('Please enter the zip/postal code.'));
}
if (empty($countryId)) {
$this->throwException(__('Please enter the country.'));
}
if (empty($address->getRegionId())) {
$this->throwException(__('Please enter the state/province.'));
}
}

/**
* @param $message
* @throws InputException
*/
private function throwException($message)
{
throw new InputException($message);
}
}

 

Magento 2 Customer API For Account Management

Now, this block class of customer API will help to coordinated and processed the data using the function of changeEmail() and changePasswordById() by passing the parameter of customer id, new email, current password, and confirm password.

app/code/Wishusucess/Customer/Api/AccountManagementInterface.php

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

/**
* Interface AccountManagementInterface
* @package Wishusucess\Customer\Api
* @api
*/
interface AccountManagementInterface
{
/**
* @param int $customerId
* @param string $newEmail
* @param string $currentPassword
* @return bool true on success
* @throws \Magento\Framework\Exception\InputException
* @throws \Magento\Framework\Exception\InvalidEmailOrPasswordException
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @throws \Magento\Framework\Exception\State\InputMismatchException
* @throws \Magento\Framework\Exception\State\UserLockedException
*/
public function changeEmail($customerId, $newEmail, $currentPassword);

/**
* Change customer password.
*
* @param int $customerId
* @param string $currentPassword
* @param string $newPassword
* @param string $confirmPassword
* @return bool true on success
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function changePasswordById($customerId, $currentPassword, $newPassword, $confirmPassword);
}

 

Magento 2 Customer API Address Repository

app/code/Wishusucess/Customer/Api/AddressRepositoryInterface.php

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

/**
* Interface AddressRepositoryInterface
* @package Wishusucess\Customer\Api
* @api
*/
interface AddressRepositoryInterface
{
/**
* Update address for the given customerId.
*
* @param int $customerId
* @param \Magento\Customer\Api\Data\AddressInterface $address
* @return \Magento\Customer\Api\Data\AddressInterface
* @throws \Magento\Framework\Exception\InputException
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function save($customerId, $address);

/**
* Delete address by the given $addressId.
*
* @param int $customerId
* @param int $addressId
* @return bool true on success
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\StateException
*/
public function deleteById($customerId, $addressId);

/**
* Retrieve address by $addressId.
*
* @param int $customerId
* @param int $addressId
* @return \Magento\Customer\Api\Data\AddressInterface
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getById($customerId, $addressId);

/**
* Retrieve address list
*
* @param int $customerId
* @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
* @return \Magento\Customer\Api\Data\AddressSearchResultsInterface
*/
public function getList($customerId, \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);
}

 

Download Customer API

 

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

Categories API Key: Get All Category List Through API Key in Magento 2

 

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

 

 

 

 

 

 

 

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

So as we all know Magento 2 needs token authentication first then only that will allow you to communicate with his data so we have to request first and then include with security token to gain access to the ContactUs REST API endpoints.

So basically we use this contact us form to link in the footer of Magento 2 shopping store. This contact us allows customers to send a message directly to the store owner which is a way to communicate with the website owner.

When a customer faces any kind of issue then they contact the website representative or help team which help them to requests or concerns resolved immediately,

Here we will communicate the customer name, email, phone and comment through the contact us Rest API keys.

app/code/Wishusucess/ContactUs/registration.php

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

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

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

app/code/Wishusucess/ContactUs/Model/ContactUsRepository.php

app/code/Wishusucess/ContactUs/Api/ContactUsInterface.php

Magento 2 ConatctUs REST API Keys

 

Register Contact US Rest API Module

app/code/Wishusucess/ContactUs/registration.php

<?php
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_ContactUs
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_ContactUs',
__DIR__
);

 

Step 2: Module Basic Information

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

<?xml version="1.0"?>
/**
* Developer: Wishusucess Magento 2x Developer Team
* Module:    Wishusucess_ContactUs
* Author:    Hemant Singh Magento 2X Developer
* 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_ContactUs" setup_version="1.0.0" />
</config>

 

Define Dependency Injection

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

<?xml version="1.0"?>
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_ContactUs
* Author: Hemant Singh Magento 2X Developer
* 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\ContactUs\Api\ContactUsInterface" type="Wishusucess\ContactUs\Model\ContactUsRepository" />
</config>

 

Create ContactUs REST API Route ID

Magento 2 Web APIs are Magento default features in Magento 2 and the onward version of Magento which help and save a lot of time for Magento 2 developers to communicate with the Magento 2 stores. They directly use their keys and can fill the contact us form from the different servers using these keys.

This file helps us define the route ID so here we have defined the route URL which is /V1/Wishusucess/contact_us and we are using the post method to send the data to the Magento store.

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

<?xml version="1.0"?>
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_ContactUs
* Author: Hemant Singh Magento 2X Developer
* 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/contact_us" method="POST">
<service class="Wishusucess\ContactUs\Api\ContactUsInterface" method="sendContactUs"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>

 

Rest API Model Class of Contact US

The model class basically we are using to send the details from the contact us form using the sendEmail() method and we are sending the data of name, email, phone, comment.

Then we will validate the data using validatedParams( ) method which checks the validation at the server-side.

app/code/Wishusucess/ContactUs/Model/ContactUsRepository.php

<?php
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_ContactUs
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
namespace Wishusucess\ContactUs\Model;
use Wishusucess\ContactUs\Api\ContactUsInterface;
use Magento\Contact\Model\MailInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;

class ContactUsRepository implements ContactUsInterface
{
/**
* @var Context
*/
private $context;

/**
* @var MailInterface
*/
private $mail;

/**
* @param Context $context
* @param MailInterface $mail
*/
public function __construct(
Context $context,
MailInterface $mail
) {
$this->context = $context;
$this->mail = $mail;
}

/**
* @inheritdoc
*/
public function sendContactUs($name, $email, $phone, $comment){
if ($this->validatedParams($name, $email, $phone, $comment)) {
try {
$this->sendEmail(["name"=>$name, "email"=>$email, "phone"=>$phone, "comment"=>$comment]);
return 'Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.';
} catch (LocalizedException $e) {
throw $e;
} catch (\Exception $e) {
throw $e;
} 
}
}

/**
* @param array $post Post data from contact form
* @return void
*/
private function sendEmail($post)
{
$this->mail->send(
$post['email'],
['data' => $post]
);
}

/**
* @return array
* @throws \Exception
*/
private function validatedParams($name, $email, $phone, $comment)
{
if (trim($name) === '') {
throw new LocalizedException(__('Enter the Name and try again.'));
}
if (trim($comment) === '') {
throw new LocalizedException(__('Enter the comment and try again.'));
}
if (false === \strpos($email, '@')) {
throw new LocalizedException(__('The email address is invalid. Verify the email address and try again.'));
}

return true;
}
}

 

Contact Us Interface in API

app/code/Wishusucess/ContactUs/Api/ContactUsInterface.php

<?php
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_ContactUs
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
namespace Wishusucess\ContactUs\Api;

/**
* @api
*/
interface ContactUsInterface
{
/**
* Contact Us
*
* @param string $name
* @param string $email
* @param string $phone
* @param string $comment
* @return string success
* @throws \Magento\Framework\Exception\AuthenticationException
*/
public function sendContactUs($name, $email, $phone, $comment);
}

 

Hire Magento 2 Expert Developer to Develop Your Store

 

Related Post:

Custom Shipping Text Filed: Show Custom Text Magento 2

Share Product on WhatsApp: With Products Image And URL in Magento 2

 

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

 

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

So here I have developed a new module which is Wishusucess Checkout REST API to communicate at the time of checkout. If you also looking to develop a mobile application using Magento 2 then this Module will help you to build your application for a mobile shopping cart using Wishusucess_Checkout keys that will help you to execute the API key successfully.

Magento 2 Checkout REST API Keys

 

Endpoint:

POST <host>/rest/<store_code>/V1/carts/mine/estimate-shipping-methods

Headers:

Content-Type: application/json

Authorization: Bearer <customer token>

Payload:

So below is the syntax to get the shipping address.

{
"address": {
"region": "New Delhi",
"region_id": 43,
"region_code": "NY",
"country_id": "India",
"street": [
"Noida Sector 62"
],
"postcode": "201303",
"city": "New Delhi",
"firstname": "Hemant",
"lastname": "Singh",
"customer_id": 4,
"email": "cs.hemantsingh@gmail.com",
"telephone": "7992293862",
"same_as_billing": 1
}
}

 

Response:

Now you will get the response something like the below data.

[
{
"carrier_code": "flatrate",
"method_code": "flatrate",
"carrier_title": "Flat Rate",
"method_title": "Fixed",
"amount": 15,
"base_amount": 15,
"available": true,
"error_message": "",
"price_excl_tax": 15,
"price_incl_tax": 15
},
{
"carrier_code": "tablerate",
"method_code": "bestway",
"carrier_title": "Best Way",
"method_title": "Table Rate",
"amount": 5,
"base_amount": 5,
"available": true,
"error_message": "",
"price_excl_tax": 5,
"price_incl_tax": 5
}
]

 

Checkout REST API Key Magento 2 Extension

Now let's start a custom module to communicate your Magento store with some other technology like ReactJS or NodeJS store.

Using this module you will get a checkout API key that will help you to communicate on another side.

Checkout API Keys Module Basic File

app/code/wishusucess/Checkout/registration.php

app/code/wishusucess/Checkout/etc/module.xml

app/code/wishusucess/Checkout/etc/di.xml

app/code/wishusucess/Checkout/etc/webapi.xml

app/code/wishusucess/Checkout/Model/CompositeConfigProvider.php

app/code/wishusucess/Checkout/Model/ConfigProviderInterface.php

app/code/wishusucess/Checkout/Model/StoreConfig.php

app/code/wishusucess/Checkout/Payment/ConfigProvider.php

app/code/wishusucess/Checkout/Api/StoreConfigInterface.php

 

Step 1: Register Your Extension

app/code/wishusucess/Checkout/registration.php

<?php
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_Checkout
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'wishusucess_Checkout',
__DIR__
);

 

Step 2: Give Module Basic Information

app/code/wishusucess/Checkout/etc/module.xml

<?xml version="1.0"?>
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_Checkout
* Author: Hemant Singh Magento 2X Developer
* 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_Checkout" setup_version="1.0.0">
<sequence>
<module name="Magento_Checkout" />
</sequence>
</module>
</config>

 

Define Dependency of REST API Keys

app/code/wishusucess/Checkout/etc/di.xml

<?xml version="1.0"?>
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_Checkout
* Author: Hemant Singh Magento 2X Developer
* 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\Checkout\Api\StoreConfigInterface" type="Wishusucess\Checkout\Model\StoreConfig"/>
<type name="Wishusucess\Checkout\Model\CompositeConfigProvider">
<arguments>
<argument name="configProviders" xsi:type="array">
<item name="payments_config_provider" xsi:type="object">Wishusucess\Checkout\Model\Payment\ConfigProvider</item>
</argument>
</arguments>
</type>
</config>

 

Step 4: Define Route ID in Your Web API File

So this is the only responsible file to generate your API keys URL address. In this file, you have to mention the route URL and the method like what kind of action you are going to perform on the particular route id. So here we are performing the POST method on the below route URL:

/V1/wishusucess/storeConfig/:cartId

app/code/wishusucess/Checkout/etc/webapi.xml

<?xml version="1.0"?>
/**
* Developer: Wishusucess Magento 2x Developer Team
* Module: Wishusucess_Checkout
* Author: Hemant Singh Magento 2X Developer
* 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/storeConfig/:cartId" method="GET">
<service class="Wishusucess\Checkout\Api\StoreConfigInterface" method="getStoreConfigsFromCart"/>
<resources>
<resource ref="anonymous" />
</resources>
</route>
</routes>

 

Step 5: Composite Config Provider

app/code/wishusucess/Checkout/Model/CompositeConfigProvider.php

<?php
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_Checkout
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
declare(strict_types=1);

namespace Wishusucess\Checkout\Model;

use Magento\Store\Model\App\Emulation;

class CompositeConfigProvider implements ConfigProviderInterface
{
/**
* @var ConfigProviderInterface[]
*/
private $configProviders;

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

/**
* @param Emulation $emulation
* @param ConfigProviderInterface[] $configProviders
*/
public function __construct(
Emulation $emulation,
array $configProviders
) {
$this->appEmulation = $emulation;
$this->configProviders = $configProviders;
}

/**
* {@inheritdoc}
*/
public function getConfig($cartId = null)
{
$config = [];
foreach ($this->configProviders as $configProvider) {
$config = array_merge_recursive($config, $configProvider->getConfig($cartId));
}
return [$config];
}
}

 

Create Model For Checkout API Config Provider Interface

app/code/wishusucess/Checkout/Model/ConfigProviderInterface.php

<?php
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_Checkout
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
namespace Wishusucess\Checkout\Model;

interface ConfigProviderInterface
{
/**
* Retrieve assoc array of checkout configuration
* @param int $cartId
* @return string[]
*/
public function getConfig($cartId = null);
}

 

Step 7: Model for Store Config

app/code/wishusucess/Checkout/Model/StoreConfig.php

<?php
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_Checkout
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
declare(strict_types=1);

namespace Wishusucess\Checkout\Model;

use Wishusucess\Checkout\Api\StoreConfigInterface;

class StoreConfig implements StoreConfigInterface
{
/**
* @var CompositeConfigProviderFactory
*/
protected $configProviderFactory;

/**
* StoreConfig constructor.
* @param CompositeConfigProviderFactory $compositeConfigProviderFactory
*/
public function __construct(
CompositeConfigProviderFactory $compositeConfigProviderFactory
) {
$this->configProviderFactory = $compositeConfigProviderFactory;
}

/**
* @inheritDoc
*/
public function getStoreConfigsFromCart($cartId)
{
return $this->configProviderFactory->create()->getConfig($cartId);
}
}

 

Magento 2 REST API Keys For Payment

app/code/wishusucess/Checkout/Payment/ConfigProvider.php

<?php
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_Checkout
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
declare(strict_types=1);

namespace Wishusucess\Checkout\Model\Payment;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Payment\Model\CcConfig;
use Magento\Quote\Api\PaymentMethodManagementInterface;
use Magento\Quote\Model\QuoteRepository;
use Wishusucess\Checkout\Model\ConfigProviderInterface;

class ConfigProvider implements ConfigProviderInterface
{
/**
* @var QuoteRepository
*/
private $quoteRepository;

/**
* @var PaymentMethodManagementInterface
*/
protected $paymentMethodManagement;

/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;

/**
* @var CcConfig
*/
private $ccConfig;

/**
* ConfigProvider constructor.
* @param QuoteRepository $quoteRepository
* @param PaymentMethodManagementInterface $paymentMethodManagement
* @param ScopeConfigInterface $scopeConfig
* @param CcConfig $ccConfig
*/
public function __construct(
QuoteRepository $quoteRepository,
PaymentMethodManagementInterface $paymentMethodManagement,
ScopeConfigInterface $scopeConfig,
CcConfig $ccConfig
) {
$this->quoteRepository = $quoteRepository;
$this->paymentMethodManagement = $paymentMethodManagement;
$this->scopeConfig = $scopeConfig;
$this->ccConfig = $ccConfig;
}


/**
* @inheritDoc
*/
public function getConfig($cartId = null)
{
if (null === $cartId) {
return ['payment' => []];
}
$paymentMethods = [];
try {
$quote = $this->quoteRepository->getActive($cartId);
foreach ($this->paymentMethodManagement->getList($quote->getId()) as $paymentMethod) {
$code = $paymentMethod->getCode();
$paymentMethods[$code] = [
'code' => $code,
'title' => $paymentMethod->getTitle(),
'instructions' => $paymentMethod->getConfigData('instructions')
];
}
} catch (NoSuchEntityException $noSuchEntityException) {
return ['payment' => []];
}

return ['payment' => $paymentMethods];
}
}

 

Magento 2 Create REST API Keys For Checkout

Now here we have to define one function getStoreConfigsFromCart($cartId) so this method will have the parameter of cart id so when we give the cart id in the REST API URL keys then that particular cart id values will show with the all details. And this method will return the value as a string which we have to define also otherwise it will through some errors.

app/code/wishusucess/Checkout/Api/StoreConfigInterface.php

<?php
/**
* Developer:Wishusucess Magento 2x Developer Team
* Module: Wishusucess_Checkout
* Author: Hemant Singh Magento 2X Developer
* Website: http://www.wishusucess.com/
*
*/
namespace Wishusucess\Checkout\Api;

/**
* Interface StoreConfigInterface
* @api
*/
interface StoreConfigInterface
{
/**
* @param int $cartId
* @return string[]
*/
public function getStoreConfigsFromCart($cartId);
}

 

Hire Magento 2 Expert Developer to Develop Your Store

 

Related Post:

Custom Shipping Text Filed: Show Custom Text Magento 2

Search AutoComplete: Magento 2 Module Add All Category for Search

Share Product on WhatsApp: With Products Image And URL in Magento 2

 

Recommended Post:

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

Magento Store: Best 36 Magento Websites Example in The World

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