Get Order API: Magento 2 Get Customer Order And Details Using API

I am creating a Magento 2 customer REST API module to get customer orders API using this web API route URL( get order API ).

So in order to get the order details first, we need to get the admin access token then we can add that tokens in the API header then we have to call order API with passing that AccessToken.

Get Order API in Magento 2

 

Create Custom Customer Orders API

I want to show here to get customer orders using Magento 2 REST API. This custom module will help you to get the customer's order in Magento 2.

In order to create a custom Magento 2 extension for customer REST  API, you have to create some basic files.

Here, I am creating a Model, Controller, and API component of the customer REST API.

app/code/Wishusucess/GetOrders/registration.php

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

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

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

app/code/Wishusucess/GetOrders/frontend/routes.xml

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

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

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

 

Step 1: Registration of Getting Order API

app/code/Wishusucess/GetOrders/registration.php

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

 

Step 2: Create Module XML File

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

<?xml version="1.0"?>
<!--
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_GetOrders 
* 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_GetOrders" setup_version="1.1.4" />
</config>

 

Step 3: Define Dependency Injection

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

<?xml version="1.0"?>
<!--
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_GetOrders 
* 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\GetOrders\Api\CustomInterface" type="Wishusucess\GetOrders\Model\Api\Custom"/>
</config>

 

Step 4: Create Web API XML for Route URL

Now, we have to decide the method and route URL to get access to the other websites. The method will decide to perform the operation over the API request and the URL will decide /V1/wishusucess/getorders/ how we can get access the details.

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

<?xml version="1.0"?>
<!--
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_GetOrders 
* 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/getorders/">
<service class="Wishusucess\GetOrders\Api\CustomInterface" method="getPost"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>

 

Step 5: Route ID

app/code/Wishusucess/GetOrders/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_GetOrders 
* 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="wishusucess" frontName="wishusucess">
<module name="Wishusucess_GetOrders" />
</route>
</router>
</config>

 

Step 6: Custom API Model for Getting Order

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

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

use Psr\Log\LoggerInterface;

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


public function __construct(
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
array $data = []
) {
$this->resultPageFactory = $resultPageFactory;
$this->orderRepository = $orderRepository;

}

/**
* @inheritdoc
*/

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

try {
$order = $this->orderRepository->get($orderid);
$object['order_info'] = $order->getData();
$object['payment_info'] =$order->getPayment()->getData();
$object['shipping_info'] =$order->getShippingAddress()->getData();
$object['billing_info'] =$order->getBillingAddress()->getData();
$resul=array();
foreach ($order->getAllItems() as $item)
{
//fetch whole item information
$resul= $item->getData();

}
$object['items'] = $resul;

// $response = json_decode(json_encode($object), true);
$response = $object;

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

 

Step 7: Index Controller in Custermer Orders API

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

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

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


public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
array $data = []
) {
$this->orderRepository = $orderRepository;
$this->data = $data;

parent::__construct($context);
}

public function execute() {
echo "<pre>";
$orderid = 12; // its called increment id
$order = $this->orderRepository->get($orderid);
$object['order_info'] = $order->getData();
$object['payment_info'] =$order->getPayment()->getData();
$object['shipping_info'] =$order->getShippingAddress()->getData();
$object['billing_info'] =$order->getBillingAddress()->getData();
$object['incrementid'] =$order->getIncrementId();
$object['grandtotal'] =$order->getGrandTotal();
$object['subtotal'] =$order->getSubtotal();
$object['customerid'] =$order->getCustomerId();
$object['customeremail'] =$order->getCustomerEmail();
$object['customerfirstname'] =$order->getCustomerFirstname();
$object['customerlastname'] =$order->getCustomerLastname();

print_r($object)

// print_r(json_decode(json_encode($object), true));

die();

}

}

 

Step 8: Create Custom Interface Customer Orders API

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

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

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

public function getPost($orderid);
}

 

Now run the below commands:

php bin/magento setup:upgrade

php bin/magento setup:di:compile

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

php bin/magento c:c

 

Now I am showing you the testing result by using this custom REST API of a customer order in Magento 2. I am showing you the result by using the postman tool to check the valid web API URL.

First, we have to create an admin token then we will pass that admin token in the header of the order rest api.

Our customer rest API endpoint (/rest/V1/wishusucess/getorders) has to call on the postman tools.

You have to remember that we can not call our rest API without using the rest API endpoint on any other server.

Magento 2 customer Get Order API

 

Download API

Related Post:

Magento 2 Top Developers In USA: Develop Your E-Commerce Websites

File Permissions: Magento 2 Ownership And File Permission At Installation

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

 

Recommended Post:

PayPal Account: How to Create New PayPal Account, Transfer

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

Magento 2 Command: List of Available Magento Command

I am a Magento developer but when I have started learning about Magento at that time I was thinking about the meaning of the CLI command and I was not getting that meaning, but here I am sharing with you that all Magento 2 commands meaning after gaining a lot of development experience.

List of Magento 2 Commands

The most common command of Magento 2 is setup: upgrade and many new developers used to run this command at every time.

So, In this article, I will discuss the Magento 2 command run and why we run the command, and what changes need what commands to reflect changes on the Magento 2 frontend or backend.

 

Magento 2 Setup: Upgrade Command

This is one of the most common commands for Magento developers so let's understand the meaning of this command.

php bin/magento setup:upgrade

And the short form of this setup upgrade command is:

php bin/magento set:up

So, When we should run this command?

This command we can run in the following case.

When we have done any changes in the setup script or when we install any Magento 2 new extension so we need to upgrade this command.

For:

  • InstallData, InstallSchema,UpgradeSchama, Upgradation
  • For any new module installation
  • In case of setup_version change in module.xml
  • After Magento 2 upgradation version

 

Static Content Deploy Magento 2

This is the second most used command in Magento 2. So whenever we do any changes in the JS file, CSS file, or HTML file then we need to generate the static content of that file so we run this command.

php bin/magento setup:static-content:deploy

And the shot for of static content deploy command in Magento 2 is:

php bin/magento s:s:d

This command is used to delete the old static generated file. In the Magento 2 developer mode no more needs to run this command.

 

Setup DI Compile Command

Whenever we use a new dependency then we need to construct that dependency in the project so we run this command.

php bin/magento setup:di:compile

This setup di compile command also has the short form command and we can use:

php bin/magento s:d:c

if we have added any new controller class then also this command is required.

 

Cache Clean and Cache Flush Magento 2 Commands

This command we use to see the reflected changes on the frontend so we clear all the Magento server cache. We use this Magento 2command in the following conditions.

  • And for admin configuration,
  • layout XML changes
  • UI component changes
  • phtml file changes
  • override HTML changes
  • js in frontend theme.
php bin/magento cache:flush

Short Form: php bin/magento c:f

 

Magento 2 Commands: Important CLI/SSH Command-List

Here, I am giving you the list of all Magento 2 available commands so it would be very easy to get all the detailed descriptions and short commands of Magento 2.

SSH Commands Shortcuts Description
Available commands:
help h
Displays help for a command
php bin/magento list php bin/magento l Lists commands
admin All Admin Command
php bin/magento admin:user:create php bin/magento a:u:c
Creates an administrator
php bin/magento admin:user:unlock php bin/magento a:u:u
Unlock Admin Account
app
php bin/magento app:config:dump
Create dump of application
php bin/magento app:config:import
Import data from shared configuration files to appropriate data storage
cache Magento 2 Avilable Cache Command
php bin/magento cache:clean php bin/magento c:c
Cleans cache type(s)
php bin/magento cache:disable php bin/magento c:d
Disables cache type(s)
php bin/magento cache:enable php bin/magento c:e
Enables cache type(s)
php bin/magento cache:flush php bin/magento c:f
Flushes cache storage used by cache type(s)
php bin/magento cache:status php bin/magento c:s
Checks cache status
catalog Catalog Realted Magento 2 Command
php bin/magento catalog:images:resize php bin/magento c:i:r
Creates resized product images
php bin/magento catalog:product:attributes:cleanup php bin/magento c:p:a:c
Removes unused product attributes.
config Change Magento 2 Configuration Command
php bin/magento config:sensitive:set
Set sensitive configuration values
php bin/magento config:set
Change system configuration
php bin/magento config:show
Shows configuration value for given path. If path is not specified, all saved values will be shown
cron All Cron Job Command in Magento 2
php bin/magento cron:install
Generates and installs crontab for the current user
php bin/magento cron:remove
Removes tasks from crontab
php bin/magento cron:run php bin/magento c:r
Runs jobs by schedule
customer Magento 2 Customer Command
php bin/magento customer:\hash:upgrade php bin/magento c:h:u
Upgrade customer’s hash according to the latest algorithm
deploy
php bin/magento deploy:mode:set php bin/magento d:m:set
Set application mode.
php bin/magento deploy:mode:show php bin/magento d:m:sho
Displays current application mode.
dev
php bin/magento dev:di:info
Provides information on Dependency Injection configuration for the Command.
php bin/magento dev:query-log:disable
Disable DB query logging
php bin/magento dev:query-log:enable
Enable DB query logging
php bin/magento dev:source-theme:deploy php bin/magento d:s:d
Collects and publishes source files for theme.
php bin/magento dev:template-hints:disable
Disable frontend template hints. A cache flush might be required.
php bin/magento dev:template-hints:enable
Enable frontend template hints. A cache flush might be required.
php bin/magento dev:tests:run php bin/magento d:t:r Runs tests
php bin/magento dev:urn-catalog:generate php bin/magento d:u:g
Generates the catalog of URNs to *.xsd mappings for the IDE to highlight xml.
php bin/magento dev:xml:convert php bin/magento d:x:c
Converts XML file using XSL style sheets
i18n Avilable Lang. Command in Magento 2
php bin/magento i18n:collect-phrases php bin/magento i1:c
Discovers phrases in the codebase
php bin/magento i18n:pack php bin/magento i:p
Saves language package
php bin/magento i18n:uninstall php bin/magento i:u
Uninstalls language packages
indexer List of indexer Command in Magento 2
php bin/magento indexer:info php bin/magento i:i
Shows allowed Indexers
php bin/magento indexer:reindex php bin/magento i:rei Reindexes Data
php bin/magento indexer:reset php bin/magento i:res
Resets indexer status to invalid
php bin/magento indexer:set-mode php bin/magento i:set
Sets index mode type
php bin/magento indexer:show-mode php bin/magento i:sho
Shows Index Mode
php bin/magento indexer:status php bin/magento i:sta
Shows status of Indexer
info
php bin/magento info:adminuri php bin/magento i:a
Displays the Magento Admin URI
php bin/magento info:backups:list php bin/magento i:b:l
Prints list of available backup files
php bin/magento info:currency:list php bin/magento i:c:l
Displays the list of available currencies
php bin/magento info:dependencies:show-framework php bin/magento i:d:show-f
Shows number of dependencies on Magento framework
php bin/magento info:dependencies:show-modules
Shows number of dependencies between modules
php bin/magento info:dependencies:show-modules-circular
Shows number of circular dependencies between modules
php bin/magento info:language:list php bin/magento i:l:l
Displays the list of available language locales
php bin/magento info:timezone:list php bin/magento i:t:l
Displays the list of available timezones
maintenance
php bin/magento maintenance:allow-ips php bin/magento m:a
Sets maintenance mode exempt IPs
php bin/magento maintenance:disable php bin/magento ma:d
Disables maintenance mode
php bin/magento maintenance:enable php bin/magento ma:e
Enables maintenance mode
php bin/magento maintenance:status php bin/magento ma:s
Displays maintenance mode status
module Magento Module Command
php bin/magento module:disable php bin/magento mo:d
Disables specified modules
php bin/magento module:enable php bin/magento mo:e
Enables specified modules
php bin/magento module:status php bin/magento mo:s
Displays status of modules
php bin/magento module:uninstall php bin/magento m:u
Uninstalls modules installed by composer
sampledata
php bin/magento sampledata:deploy php bin/magento sa:d
Deploy sample data modules
php bin/magento sampledata:remove php bin/magento sa:rem
Remove all sample data packages from composer.json
php bin/magento sampledata:reset php bin/magento sa:res
Reset all sample data modules for re-installation
setup
php bin/magento setup:backup php bin/magento s:b
Takes backup of Magento Application code base, media and database
php bin/magento setup:config:set php bin/magento s:c:s
Creates or modifies the deployment configuration
php bin/magento setup:cron:run php bin/magento s:c:r
Runs cron job scheduled for setup application
php bin/magento setup:db-data:upgrade php bin/magento s:db-d:u
Installs and upgrades data in the DB
php bin/magento setup:db-schema:upgrade php bin/magento s:db-s:u
Installs and upgrades the DB schema
php bin/magento setup:db:status php bin/magento s:d:s
Checks if DB schema or data requires upgrade
php bin/magento setup:di:compile php bin/magento s:d:c
Generates DI configuration and all missing classes that can be auto-generated
php bin/magento setup:install php bin/magento s:i
Installs the Magento application
php bin/magento setup:performance:generate-fixtures php bin/magento s:p:g
Generates fixtures
php bin/magento setup:rollback php bin/magento se:r
Rolls back Magento Application codebase, media and database
php bin/magento setup:static-content:deploy php bin/magento s:s:d
Deploys static view files
php bin/magento setup:store-config:set php bin/magento s:s:s
Installs the store configuration. Deprecated since 2.2.0. Use config:set instead
php bin/magento setup:uninstall php bin/magento s:un
Uninstalls the Magento application
php bin/magento setup:upgrade php bin/magento s:up
Upgrades the Magento application, DB data, and schema
store
php bin/magento store:list
Displays the list of stores
store:website:list
Displays the list of websites
theme
php bin/magento theme:uninstall php bin/magento t:u
Uninstalls theme
varnish
php bin/magento varnish:vcl:ge

 

These all are Magento 2 default commands, we can create a custom SSH/CLI command in Magento 2, so that is all are different topics and we will discuss it in another post.

 

Related Post:

Magento 2 Top Developers In USA: Develop Your E-Commerce Websites

File Permissions: Magento 2 Ownership And File Permission At Installation

 

Recommend Post:

eCommerce Framework: Magento 2 eCommerce Developers in India

Magento Store: Best 36 Magento Websites Example in The World

 

Top Magento 2 Free Extension For Banner Image Slider

In this article, I am going to explain how we can add banner image sliders on the home page, category page, cms page, or block page in Magento 2 websites.

Wishusucess Magento 2 Banner Slider Free Extension

This extension helps you t add a banner image in your store which makes your store beautiful and appealing to the customer through installing a Wishusucess free banner slider extension.

By adding these slideshows extension websites look wonderful with magnificent slide effects with Magento 2 Wishusucess free module.

 

Wishusucess Banner Image Sliders

Allows you to create a banner for your stores and you can call that banner anywhere to promote your website. By adding these banner images usually, we can show the target information to the customer.

Moreover, the Wishusucess slider extension makes your store beautiful and attractive.

  • No needs to add extra code in your store.
  • very little time takes to add your banner slider Images on your desire pages.
  • Sliders banner Improve customer experience.
  • By adding this banner you can target specific information for the customer.
  • Banner to introduce business
  • Increase Click-Through-Rate(CTR) by installing this banner module. so its increases promotions and sales.T
  • No other dependencies are required.
  • Wishusucess banner Images extension is compatible with all Magento 2 versions, from Magento 2.0, Magento 2.1, Magento 2.2, Magento 2.3, Magento 2.4, etc.

 

Banner Images Sliders Compatibility

There is no other coding is required so, you can use the Banner Slider extension on any page like you can use it for Home Page Banner Slider, category page banner slider, cms page banner slider, block images slider.

 

Advantages of Wishusucess Banner Image Sliders

You can make your store too attractive just by installing this module. So when you add this slider you will have the option to make it appealing and informative for the customer.

  • Attractive slideshows

When the banner is informative and attractive then customers can easily get engaged with the product and that will increase sales Because it attracts customers' attention through the informative image.

  • Customers always pay attention to moving images.

With a gorgeous banner image slideshow, your store will have the extra capabilities to grab the attention of your customers.

It provides an images slider flexibly so you can add any page on your store like homepage, category page, product page, CMS page.

- It has the extra customization functionality in admin so you can increase the slider speed or decrease the slider speed.

 

How to Install Magento 2 Banner Slider Extension

Just visit our official Github directory and download the  Wishusucess Slider Extension and paste it into your Magento root app/code directory.

Download Wishusucess Images Slider

 

Run The Following Command in Magento 2 Root Folder:

php bin/magento setup:upgrade

php bin/magento setup:di:compile

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

php bin/magento cache:clean

 

Hire Magento 2 Developers for your Stores

Banner image Sliders in Magento 2

You can add image video, image as a banner slider

Also, you can change the configuration of sliders.

Magento 2 Banner Image Sliders

 

Related Post:

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

File Permissions: Magento 2 Ownership And File Permission At Installation

 

Recommended Post:

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

Magento 2 Top Developers In USA: Develop Your E-Commerce Websites

Wihsuscess is a Team Of Magento Expert Developer, We help to build Online Shopping Websites using the Magento eCommerce platform that uses the capabilities and the features of Magento custom development and increases business productivity. We are going to give you the information about Magento 2 top developers in usa.

We are experts in each section of Magento like development, customization, designing, optimization, integration features of Magento commerce. Our Magento experts team will give you leading digital experiences in the largest global brands.

Magento 2 Top Developers in USA in 2021

 

Perks of Hiring Wishusucess Magento Team

Magento is a leading platform in the e-commerce open-source sector and in the global reviews of developers and various users it's considered as one of the best open-source platforms.

So basically Magento has very vast reliability, scalability, and excellent functionality so it's considered one of the best frameworks.

Apart from this, the functionality of Magento also saves a lot of time to developed and customize the stores so the majority of the business owners can afford its cost affordability and time-saving capabilities.

However, due to lots of excellent functionality only experience Magento developers can able to build a flawless Magento store, so it's commonly understood for business owners to get hire one of the best Magento experts in the world.

With the help of Wishusucess Magento, Expert Developers Website Development Team you can build your eCommerce website by yourself.

So if you are seeking Magento Expert Professionals please connect with us, we are here to save you lots of time and money and can build your site within some hours.

 

Magento 2 Top Developers in USA

The top Magento Development company Wishusucess has delivered more than 60+ projects in last 5 years with 100% client satisfaction.

Wishuscess Magento expert team services are crafted to achieve client requirements with an amicable customer experience. However, before hiring any Magento professional please check the following pointers which help you to decide your ideal developers.

  • You can Check the Wishuscess Magento teamwork portfolio.
  • We have more sophisticated developers.
  • All Magento Developers are Magento Certified Developers.
  • Our developers have professional accreditation as certified Magento developers.
  • There is a list of Client Testimonials of the Wishusucess Team.
  • We have developed more than 160+ free Magento extensions that are available on github.
  • We provide a minimum of 6 months of free technical support post-project delivery.

 

Magento Technical Support Post Project

Technical support is a very important aspect of any e-commerce project but when it comes to the Magento framework then it's real to create a critical movement.

Our Team support 6-month free technical support after the project delivery and then you can extend this service one more time for 6 months at the very minimum cost.

 

Magento 2 Top Developers in USA 2021

eCommerce Framework: Magento 2 eCommerce Developers in India

When you choose any development agency then the first thing which we have to consider is that e-commerce web development is not a short-term project. It's taking time for the quality of work.

So wherever you hired a team then you have to keep in mind that it's going to take time and It’slong process of constant updates and maintenance by the expert web developers so that consumes time and hours which will cost you very high.

So choose your developers very wisely they should know the exact problem then only they will know how quickly that should be resolvable.

 

Top Magento Development Company in the USA

So, looking for the best Magento Development company in the USA we have to keep in mind that certified and experienced developers at a low cost. Wishusucess Team is available at a very cost which is affordable and reliable to the project.

Our team of eCommerce projects has immense experience in the development and customization of Magento stores.

We have done a lot of research about Magento e-commerce development companies and found the list of best companies but when it comes to the price and per hour rate then we didn't find any other companies who can work at a very attractive cost so anyone can easily hire their developers.

But Wishusucess has certified developers to hire for your projects. Hemant Singh certified Magento developer has successfully completed his 45+ eCommerce development projects.

So when it comes to matching experience with other developers at the same cost then obviously you will have plus pointers.

 

Magento Store: Best 36 Magento Websites Example in The World

File Permissions: Magento 2 Ownership And File Permission At Installation

I am going to explain about Magento 2 file permissions while installation of your Magento 2 framework. It is very necessary to give the correct file permission otherwise Magento 2 store will not work properly or that will show you the CSS and JS loading when you open the website.

 

Correct File Permissions in Magento 2

In this section first I will discuss how you set up the ownership of your Magento 2 root directory permission.

It would be different based on the Magento store mode of your development and production system.

So when you install the Magento you should give ownership of the file before the installation and here you will get to know what would be that ownership.

Based on User Requirments:

One User: In this section, we allow only one user access like you the only person who hosting the websites and managing the website, and developing the website.

Two users: In this section, we usually decide one is a developer and the second is a web server hosting manager so that manager will have all kinds of permission. This is one of the safest ways to set up the store.

The web server user can access the store frontend and admin panel.

 

File Permissions For default or Developer Mode Store Magento

In this section, we will understand what should be the correct permission for default or developer mode.

So the following directories should be writable by both Magento users in developer and default mode:

  • var
  • generated
  • pub/static
  • pub/media
  • app/etc

Remember you have to apply for the setgid permission so that will apply for inside files and folders as well.

find var generated pub/static pub/media app/etc -type f -exec chmod g+w {} +
find var generated pub/static pub/media app/etc -type d -exec chmod g+ws {} +

 

Magento 2 Production mode Files Permission

When we move our website from the development server or staging server to the live site so we have to change the Magento deploy mode.

So now remove write access from files in the following directories otherwise that will create security problems for your site.

  • vendor
  • app/code
  • app/etc
  • lib
  • pub/static
  • Any other static resources
  • generated/code
  • generated/metadata
  • var/view_preprocessed
code directories: read-only mode

Now change to production mode:

bin/magento deploy:mode:set production

Enter the following command as a user with root privileges:

find app/code lib pub/static app/etc generated/code generated/metadata var/view_preprocessed \( -type d -or -type f \) -exec chmod g-w {} + && chmod o-rwx app/etc/env.php

Note: So whenever you run some update command then you have to change the code directory file permission from reading mode to write mode then run the command.

find app/code lib var generated vendor pub/static pub/media app/etc \( -type d -or -type f \) -exec chmod g+w {} + && chmod o+rwx app/etc/env.php

 

Already Installed But Not Loading CSS, JS

If you have already installed a Magento 2 framework but just after the fresh installation, you are not able to access your store successfully then try the below permission.

Go to the installation directory of your store.

cd wishusucess

// 644 permission for files
find . -type f -exec chmod 644 {} \; 

// 755 permission for directory
find . -type d -exec chmod 755 {} \;

chmod 644 ./app/etc/*.xml

chown -R :<web server group> .

chmod u+x bin/magento

 

Magento 2 Admin Not Found Problem

If the problem is not been solved then try the below steps you will defiantly get the solution to your store loading problem.

Sometimes it happens because of the wrong file permission and when Magento not getting correct access to the files at the time of execution.

So its show error like below image, its shows Magento admin not found issue or frontend not loading correctly issues.File Permissions in Magento 2

If you are still facing the same problem as the above image then try the below steps.

Go to the Installation Directory

cd wishusucess

Now run the below command

sudo chmod -R 777 /

sudo a2enmod rewrite

sudo service apache2 restart

Now run this:

sudo gedit /etc/apache2/apache2.conf

Note: Sometimes it's not working then you have to go into the root user first then type the below command otherwise it will show you the same error.

gedit /etc/apache2/apache2.conf

you can exit from the root user

Now run below command in the magento root direcotry.

rm -rf var/di/* var/generation/* var/cache/* var/log/* var/page_cache/* var/session/* var/view_preprocessed/* pub/static/*

Now you have to edit the apache config setting so for that:

Replace this code :

<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride none
Require all granted

with

<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted

Note: Here we have changed AllowOverride None to AllowOverride All

Now run command:

sudo service apache2 restart

Now, run below command

php bin/magento setup:upgrade

php bin/magento setup:di:compile

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

Magento 2 Loading Issues of Websites

 

Related Post:

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

Elasticsearch: How to Install Elasticsearch in Ubuntu 18.04

 

Recommended Post:

eCommerce Framework: Magento 2 eCommerce Developers in India

 

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

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

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

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

Magento 2 Shipping Address API

 

Why Shipping Address APIs?

No more complicated code is required for integration.

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

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

 

Step 1: Shipping API Registration

app/code/Wishusucess/ShippingAddress/registration.php

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

 

Step 2: Module Name & Information

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

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

 

Step 3: Give Preference of API

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

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

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

 

Step 3: Route Method And URL

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

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

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

 

Step 4: Decide Route ID

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

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

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

 

Step 5: Shipping Address API Model Class

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

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

use Psr\Log\LoggerInterface;

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

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



}

/**
* @inheritdoc
*/

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

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

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


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

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

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


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

 

Step 6: Controller To Execute API

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

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

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

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

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

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


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

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

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


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


echo "<pre>";

print_r($customer->getData());

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

die();

}

}

 

Step 7: API for Custom Interface

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

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

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

public function getPost($customerId);
}

 

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

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

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

 

Download API

Related Post:

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

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

 

Recommend Post:

Elasticsearch: How to Install Elasticsearch in Ubuntu 18.04

 

 

 

 

eCommerce Framework: Magento 2 eCommerce Developers in India

Nowadays, eCommerce is on booming because it's an internet era. And most of the people who have some kind of business ideas and want to open their offline store also want to have an online shopping store for their offline stores so eCommerce Framework on huge demand in future.

This online shopping has drastically changed the shopping pattern nowadays. and now most of the people love buying their stuff in the line stores only.

So then people have a lot of options to develop their online shopping website using different technology and obviously, Magento is one of them.

By using the Magento content management system we can develop websites like Amazon, Flipkart, eBay, etc. that can handle the extreme requests 24*7 without any extra effort.

Magento 2 eCommerce Framework Developers in India 2021

 

eCommerce Framework in 2021

So I am defining first about commerce, An eCommerce framework allows you to develop an online shopping website without using a lot of effort. This means you just have to install the framework and you can design your frontend according to your design and then start selling your product.

You just have to configure the payment system and that shit, no any other extra thing you have to implement to start your e-commerce store.

But if you want to add extra functionality then you can add or override the core functionality extending the module or class.

So the biggest question is how efficient the available e-commerce framework is in the market.

 

eCommerce Frameworks Types

Magento offers you three primary types of eCommerce frameworks. So you can choose as per your requirements. All the Magento tyes have different functionality to work. These stores will have their own strengths and weaknesses.

Magento ECommerce Platform

Zen Cart Platform

OpenCart Platform

PrestaShop Shopping Platform

Drupal Commerce

Shopify Shopping Plateform

Woocommerce

 

Magento Frameworks Types Are:

  • SaaS.
  • Open-source.
  • Headless commerce.

 

Key Features of Magento 2 eCommerce

All the Magento version and tyes have their own key features over the security, product catalog, checkout, etc. But here, I am talking about the most common features which need in all kinds of eCommerce frameworks.

Product Management:

When it comes to product management then Magento is really a very nice framework. it can handle millions of products without any trouble.

This framework offers you 6 types of products:

  1. Simple Products
  2. Virtual Products
  3. Configurable Products
  4. Bundle Products
  5. Groped Products
  6. DownloadableProducts

This admin side of product Management is really very nice you can add all kinds of products from Admin > Catalog > Add Product, Product using a separate category.

 

Mobile Supported eCommerce

Nowadays 75% of customers are buying products from mobile so we need an extremely mobile-supported framework and Magento commerce is one of them.

This framework let you pick various kind of payment methods like integration of popular mobile payment methods such as Apple Pay, Google Pay, PayPal, Amazon Pay, and others.

 

Security in Magento Stores

Online shopping stores are always targeted by hackers so shopping stores security is one of the supreme priority tasks.

Magento sites always release time-to-time security patches which help stores keep secure from the hackers.

In other files, you can set the disallow access according to your priority of origin.

So in the commerce store sites owner are responsible to keep customer data secure otherwise it will break the security breaches.

 

Built-in SEO Capabilities.

There are many e-commerce frameworks that offer this functionality for their user's but Magento SEO facilities are on another level.

It supports improved SEO capabilities, SEO URL rewrites functionalities including control over your URLs, title tags, header tags, and metadata.

Search engine optimization (SEO) is one of the biggest reasons to succeed your online e-commerce business and Magento has really understood its user requirements.

Best SEO Agencies and Their Pricing Plan

 

Extensive plugins or Integrations

By using a variety of plugins you can change your store behavior completely as per your requirement and also it's very easy to implement the new plugin for Magento developers.

This framework also offers easy migration of your old version store into a newer version of the Magento store easily.

There are a lot of default tools of integration of Magento stores with different framework websites and technology by using the integration tool .

 

Select the Best Ecommerce Framework 2021

Most of the shopping platforms have a lot of features which is completely out of the box, which make little complex to customize as per the design but it's making set-up quick and easy.

So you can decide your platform by comparing your needs and and requirement fulfilment then set up your shopping website.

 

Related Post:

Magento Store: Best 36 Magento Websites Example in The World

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

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

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

 

Create Product Yes/No Attribute

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

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

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

 

Step 1: Registration of LatestProductsApi

app/code/Wishusucess/LatestProductsApi/registration.php

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

 

Step 2: Module Basic Information

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

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

 

Step 3: Declare Dependency of Module

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

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

 

Step 4: Latest Products API Routing URL

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

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

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

 

Step 6: Routes URL ID

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

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

 

Step 7: Controller Index File

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

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

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

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

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

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

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

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

print_r($cart);
die();

}

}

 

Step 8: Model Class Latest Products API

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

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

use Psr\Log\LoggerInterface;

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

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


}

/**
* @inheritdoc
*/

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

try {

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

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


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

 

Step 9: Latest Products API Interface

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

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

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

public function getPost();
}

 

Now Run Bellow Command:

php/bin magento setup:upgrade

php/bin magento setup:di:compile

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

php/bin magento c:c

 

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

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

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

Magento 2 Admin Access Token

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

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

Authorization: Bearer Token

Content-Type: application/JSON

Method: POST

Payload: Not Required

Authorise Your Request With Token

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

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

So all the enabled lasted product is loading here.

Call Latest Products API

Related Post:

How To GET Products List Using Magento 2 REST API

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

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

 

Recommended Post:

Elasticsearch: How to Install Elasticsearch in Ubuntu 18.04

Download Latest Product Custom Module on GitHub

 

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

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

Magento 2 CMS REST API

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

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

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

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

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

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

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

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

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

 

Searching Using CMS REST API

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

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

 

Available Endpoints Wishusucess_CMSApi

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

You just have to call the below endpoints:

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

You can retrieves page information based on the page id

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

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

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

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

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

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

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

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

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

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

 

 

Step 1: Registration CMSApi

app/code/Wishusucess/CmsApi/registration.php

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

 

Step 2: Basic Information About CMSApi

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

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

 

Step 3: Dependency Injection of Module CMSApi

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

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

 

Step 4: Route URL of CMS REST API

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

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

 

Step 5: CMSApi Block Model

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

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

use Wishusucess\CmsApi\Api\Data\BlockInterface;

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

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

return $this;
}
}

 

Step 6: Model Class for Block Manager

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

return $block;
}

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

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

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

return $block;
}

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

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

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

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

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

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

return $searchResults;
}

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

return $emulatedResult;
}
}

 

Step 7: CMSApi Model Manager for Search Criteria

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

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

use Magento\Framework\Api\SearchCriteriaInterface;

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

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

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

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

 

Step 8: CMS API For Page Model

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

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

use Wishusucess\CmsApi\Api\Data\PageInterface;

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

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

return $this;
}
}

 

Step 9: Page Manager CMS REST API

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

return $page;
}

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

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

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

return $page;
}

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

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

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

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

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

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

return $searchResults;
}

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

return $emulatedResult;
}
}

 

Step 10: Block Manager Class of CMSApi

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

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

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

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

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

 

Step 11: Page Manager Interface

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

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

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

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

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

 

Step 12: Block Interface of API

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

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

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

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

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

 

Step 13: Search Result Interface

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

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

use Magento\Framework\Api\SearchResultsInterface;

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

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

 

Step 14: Get Page Store Id

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

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

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

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

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

 

Step 15: Page Search Result Interface

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

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

use Magento\Framework\Api\SearchResultsInterface;

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

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

 

Related Post:

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

How To Call Magento 2 REST API For Customer Account Update

How To GET Products List Using Magento 2 REST API

 

Recommended Post

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

 

Download API

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

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

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

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

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

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

 

Step 1: Create Admin Access Token

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

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

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

Method: POST

Content-Type: JSON

Payload: Admin Details (Admin User and Admin Password)

 

Admin Token Access in Magento 2

Now we have received an admin access token.

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

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

 

Step 2: CMS Page REST API Request

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

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

So our actual request with getting method looks like below url

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

Method: GET

Payload: None

Header: Authorization

Content-Type: application/JSON

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

 

Magento 2 CMS Page REST API

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

 

Conclusion:

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

 

Related Post:

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

How To Call Magento 2 REST API For Customer Account Update

 

Recommended Post:

Magento Store: Best 36 Magento Websites Example in The World