Magento 2 REST API – Calling Restful Web Service GET and POST

cronmagento2modulerest apiweb services

Any one knows how to call restful web service from Magento 2?

Please guide me with a format how it can be done.

Any links to guide me with examples of POST or GET etc.

I want to Call below URL in Magento, Please suggest me structure of module

http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo

This URL results with following Data:

{
status: {
message: "the daily limit of 30000 credits for demo has been exceeded. Please use an application specific account. Do not use the demo account for your application.",
value: 18,
    }
}

Do I have to create a module? if not where I need to Call this URL?

Thanks in Advance!

Best Answer

You can create a custom module and use curl in your controller action to call this URL and Fetch response body

Curl Example (Sharing the required fragments of the file)

use Magento\Framework\HTTP\Client\Curl;
class Curlex extends AbstractHelper {
        /**
        * @var \Magento\Framework\HTTP\Client\Curl
        */
        protected $_curl;

      public function __construct(Curl $curl) 
        {

            $this->_curl =$curl;
        }
         /**
         * Send SMS
         * @param type $mobile_no
         * @param type $body
         */
        public function getResponse($url)
        {
          $url = urlencode($url);  
          $this->_curl->get($url);
          $response = $this->_curl->getBody();

         return $response
        }

}

the above example is for GET you can use for similar way (Guide for Curl with post data)

Related Topic