Magento Rest APIs to fetch all country and region by country code
Posted By : Prahalad Singh Ranawat | 25-May-2022
In Magento 2.x we can fetch all the regions and countries and also we can fetch all the regions of the specific country by passing a country code. In this article, we will create Rest APIs to fetch all regions and countries. So first of all we will create a new module or we can use a custom module to create these Rest APIs.
Module Structure:
Oodles/YumiAPI
-Api/Countryregion
-CountryregionInterface.php
-etc
-di.xml
-webapi.xml
-module.xml
-Model/Countryregion
-Countryregion.php
-registration.php
You can use the steps provided here to add a custom module for fetching country and region data using rest apis.
Step 1) Create registration.php
-Oodles/YumiAPI/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Oodles_YumiAPI',
__DIR__
);
Step 2) Create module.xml file
-Oodles/YumiAPI/etc/module.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Oodles_YumiAPI" setup_version="0.0.1"/>
</config>
Step 3) Create CountryregionInterface.php file to create your method
-Oodles/YumiAPI/Api/Countryregion/CountryregionInterface.php
<?php
namespace Oodles\YumiAPI\Api\Countryregion;
interface CountryregionInterface
{
/**
* Get country options list.
*
* @return array
*/
public function getAllCountry();
/**
* Returns json data after processing to Countryregion
*
* @api
* @return bool json data after processing to Countryregion.
*/
public function getAllRegion();
}
Step 4) Create Countryregion.php file to add logic and DI code.
-Oodles/YumiAPI/Model/Countryregion/Countryregion.php
<?php
declare(strict_types=1);
namespace Oodles\YumiAPI\Model\Countryregion;
use Magento\Framework\App\RequestInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Directory\Model\Country as country;
use Magento\Directory\Model\CountryFactory;
use Magento\Directory\Model\ResourceModel\Country\CollectionFactory as CountryCollectionFactory;
use Magento\Directory\Model\ResourceModel\Region\CollectionFactory as RegionCollectionFactory;
use Oodles\YumiAPI\Api\Countryregion\CountryregionInterface;
class Countryregion implements CountryregionInterface
{
protected $country;
protected $countryFactory;
protected $storeManager;
/**
*
* @param StoreManagerInterface $storeManager
*/
protected $request;
/**
*
* @param RequestInterface $request
*/
protected $countryCollectionFactory;
/**
*
* @param countryCollectionFactory $countryCollectionFactory
*/
protected $regionCollectionFactory;
/**
*
* @param regionCollectionFactory $regionCollectionFactory
*/
public function __construct(
RequestInterface $request,
CountryCollectionFactory $countryCollectionFactory,
RegionCollectionFactory $regionCollectionFactory,
StoreManagerInterface $storeManager = null,
country $country,
countryFactory $countryFactory
) {
$this->request = $request;
$this->country = $country;
$this->countryCollectionFactory = $countryCollectionFactory;
$this->regionCollectionFactory = $regionCollectionFactory;
$this->storeManager = $storeManager;
$this->countryFactory = $countryFactory;
}
/**
* {@inheritdoc}
*/
public function getAllCountry()
{
$collection = $this->countryCollectionFactory->create()->loadByStore();
$counties = $collection->getData();
$res = array();
$count = 0;
foreach($counties as $country) {
$res[$count]['country_id'] = $country['country_id'];
$countryy = $this->countryFactory->create()->loadByCode($country['country_id']);
$res[$count]['country'] = $countryy->getName();
$count++;
}
return $res;
}
/**
* Returns json data after processing to Countryregion
*
* @api
* @return bool json data after processing to Countryregion.
*/
public function getAllRegion(){
$countryCode = $this->request->getParam('country_id');
$regionCollection = $this->country->loadByCode($countryCode)->getRegions();
$regions = $regionCollection->loadData()->toOptionArray(false);
return $regions;
}
}
Step 5) Now we need to add CountryregionInterface.php into di.xml
- Oodles/YumiAPI/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Oodles\YumiAPI\Api\Countryregion\CountryregionInterface" type="Oodles\YumiAPI\Model\Countryregion\Countryregion" />
</config>
Step 6) Finally we need to add webapi.xml file to register our api
- Oodles/YumiAPI/etc/webapi.xml
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/yumimage/getallcountry" method="GET">
<service class="Oodles\YumiAPI\Api\Countryregion\CountryregionInterface" method="getAllCountry"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
<route url="/V1/yumimage/getallregionbycid" method="GET">
<service class="Oodles\YumiAPI\Api\Countryregion\CountryregionInterface" method="getAllRegion"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>
Endpoint of APIs: GET
- To fetch all country - {{base_url}}/rest/V1/yumimage/getallcountry
- To fetch regions of the specific country by passing a country code (pass in api url country code that you will get in getallcountry api response) - {{base_url}}/rest/V1/yumimage/getallregionbycid?country_id=IN
get all country response:
[
{
"country_id": "AD",
"country": "Andorra"
},
{
"country_id": "AE",
"country": "United Arab Emirates"
},
{
"country_id": "AF",
"country": "Afghanistan"
},
{
"country_id": "AG",
"country": "Antigua & Barbuda"
},
{
"country_id": "AI",
"country": "Anguilla"
},
{
"country_id": "AL",
"country": "Albania"
},
{
"country_id": "AM",
"country": "Armenia"
},
{
"country_id": "AN",
"country": null
},
{
"country_id": "AO",
"country": "Angola"
},
{
"country_id": "AQ",
"country": "Antarctica"
},
{
"country_id": "AR",
"country": "Argentina"
},
{
"country_id": "AS",
"country": "American Samoa"
},
{
"country_id": "AT",
"country": "Austria"
},
{
"country_id": "AU",
"country": "Australia"
},
{
"country_id": "AW",
"country": "Aruba"
},
{
"country_id": "AX",
"country": "Åland Islands"
},
{
"country_id": "AZ",
"country": "Azerbaijan"
},
{
"country_id": "BA",
"country": "Bosnia & Herzegovina"
},
{
"country_id": "BB",
"country": "Barbados"
},
{
"country_id": "BD",
"country": "Bangladesh"
},
{
"country_id": "BE",
"country": "Belgium"
},
{
"country_id": "BF",
"country": "Burkina Faso"
},
{
"country_id": "BG",
"country": "Bulgaria"
},
{
"country_id": "BH",
"country": "Bahrain"
},
{
"country_id": "BI",
"country": "Burundi"
},
{
"country_id": "BJ",
"country": "Benin"
}
]
2) get regions by country id response: rest/V1/yumimage/getallregionbycid?country_id=IN
[
{
"title": "",
"value": "",
"label": "Please select a region, state or province."
},
{
"value": "533",
"title": "Andaman and Nicobar Islands",
"country_id": "IN",
"label": "Andaman and Nicobar Islands"
},
{
"value": "534",
"title": "Andhra Pradesh",
"country_id": "IN",
"label": "Andhra Pradesh"
},
{
"value": "535",
"title": "Arunachal Pradesh",
"country_id": "IN",
"label": "Arunachal Pradesh"
},
{
"value": "536",
"title": "Assam",
"country_id": "IN",
"label": "Assam"
},
{
"value": "537",
"title": "Bihar",
"country_id": "IN",
"label": "Bihar"
},
{
"value": "538",
"title": "Chandigarh",
"country_id": "IN",
"label": "Chandigarh"
},
{
"value": "539",
"title": "Chhattisgarh",
"country_id": "IN",
"label": "Chhattisgarh"
},
{
"value": "540",
"title": "Dadra and Nagar Haveli",
"country_id": "IN",
"label": "Dadra and Nagar Haveli"
},
{
"value": "541",
"title": "Daman and Diu",
"country_id": "IN",
"label": "Daman and Diu"
},
{
"value": "542",
"title": "Delhi",
"country_id": "IN",
"label": "Delhi"
},
{
"value": "543",
"title": "Goa",
"country_id": "IN",
"label": "Goa"
},
{
"value": "544",
"title": "Gujarat",
"country_id": "IN",
"label": "Gujarat"
},
{
"value": "545",
"title": "Haryana",
"country_id": "IN",
"label": "Haryana"
},
{
"value": "546",
"title": "Himachal Pradesh",
"country_id": "IN",
"label": "Himachal Pradesh"
},
{
"value": "547",
"title": "Jammu and Kashmir",
"country_id": "IN",
"label": "Jammu and Kashmir"
},
{
"value": "548",
"title": "Jharkhand",
"country_id": "IN",
"label": "Jharkhand"
},
{
"value": "549",
"title": "Karnataka",
"country_id": "IN",
"label": "Karnataka"
},
{
"value": "550",
"title": "Kerala",
"country_id": "IN",
"label": "Kerala"
},
{
"value": "551",
"title": "Lakshadweep",
"country_id": "IN",
"label": "Lakshadweep"
},
{
"value": "552",
"title": "Madhya Pradesh",
"country_id": "IN",
"label": "Madhya Pradesh"
},
{
"value": "553",
"title": "Maharashtra",
"country_id": "IN",
"label": "Maharashtra"
},
{
"value": "554",
"title": "Manipur",
"country_id": "IN",
"label": "Manipur"
},
{
"value": "555",
"title": "Meghalaya",
"country_id": "IN",
"label": "Meghalaya"
},
{
"value": "556",
"title": "Mizoram",
"country_id": "IN",
"label": "Mizoram"
},
{
"value": "557",
"title": "Nagaland",
"country_id": "IN",
"label": "Nagaland"
},
{
"value": "558",
"title": "Odisha",
"country_id": "IN",
"label": "Odisha"
},
{
"value": "559",
"title": "Puducherry",
"country_id": "IN",
"label": "Puducherry"
},
{
"value": "560",
"title": "Punjab",
"country_id": "IN",
"label": "Punjab"
},
{
"value": "561",
"title": "Rajasthan",
"country_id": "IN",
"label": "Rajasthan"
},
{
"value": "562",
"title": "Sikkim",
"country_id": "IN",
"label": "Sikkim"
},
{
"value": "563",
"title": "Tamil Nadu",
"country_id": "IN",
"label": "Tamil Nadu"
},
{
"value": "564",
"title": "Telangana",
"country_id": "IN",
"label": "Telangana"
},
{
"value": "565",
"title": "Tripura",
"country_id": "IN",
"label": "Tripura"
},
{
"value": "566",
"title": "Uttar Pradesh",
"country_id": "IN",
"label": "Uttar Pradesh"
},
{
"value": "567",
"title": "Uttarakhand",
"country_id": "IN",
"label": "Uttarakhand"
},
{
"value": "568",
"title": "West Bengal",
"country_id": "IN",
"label": "West Bengal"
}
]
If you are looking for eCommerce store development or Magento 2.x-based development solutions, feel free to contact us at [email protected].Our experts will get back to you.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Prahalad Singh Ranawat
Prahalad Singh Ranawat is a highly skilled backend developer with extensive experience in PHP, Laravel, Magento, Headless Magento, RESTful API, Node.js, and Vue.js. He also possesses knowledge in Shopify. Prahalad has a solid background in working with Postman, Swagger, Git, MySQL, MongoDB, and the LAMP stack. With his passion for learning and creativity, he is constantly exploring new technologies to enhance his skills. He has provided DevOps support and contributed his expertise to a range of projects, including Yumi Paws, OACustomer-Dashboard, Vlad Application, Information Sharing Website, Eating Disorder Intervention, TRO Platform, and SimplyNoted.