Loading...

How to make curl request in Magento 2? A Beginners Guide

Pravin Prajapati  ·   12 Jan 2024
curl request in Magento 2
service-banner

Introduction to Curl Requests

Understanding curl requests is required for interacting with APIs and integrating external services into your Magento store, whether you're a developer or a store owner. For those using Magento 2, integrating Curl into your website can vastly improve its performance and potential.

Are you working in Magento 2 and need to know how to create a cURL request? You are in the right place. Here, we know in-depth about curl requests and see how they can improve your Magento 2 experience. This guide is perfect for those new to Magento 2, as it takes you step by step to help you create a curl request.

What is Curl?

Client URL (pronounced "curl") is a command line program that sends data between a device and a server via a terminal. A user defines a server URL (where they want to submit a request) and the data they want to transmit to that server URL using this command line interface (CLI).

API tools such as Postman and Insomnia provide an interactive User Interface (UI) that enables you to make various requests to URLs and receive and process queries. The cURL command does the same function but in your terminal. cURL is available for Linux, Mac, and Windows.

The cURL command makes use of the client-side URL transfer library libcURL. This module supports transmission protocols, including HTTPS, SMTP, and FTP. You may also include cookies, create proxies, and add login credentials when making requests.

cURL may be used to test APIs, retrieve data from sources, test websites, and track redirection from the terminal. Because of its simplicity and strength, it is a popular choice for communicating with APIs and online services.

Why use Curl in Magento 2?

cURL is a helpful tool that can significantly increase the performance and functionality of an e-commerce website. Numerous benefits can be achieved by incorporating cURL into the website's coding and architecture.

One of the main advantages of using CURL is its ability to improve website speed and loading times. cURL helps decrease the time it takes for the website to process and display information. cURL provides smooth communication between the website and various external APIs. The cURl offers real-time inventory tracking, shipping information retrieval, and secure payment processing, enhancing the customer experience and streamlining business website management.

cURL offers a high level of security for e-commerce websites. As a library for transferring data securely, it ensures that sensitive information, such as customer data and payment details, is transmitted safely and without any risk of interception or manipulation. This instils trust in customers and helps build a positive reputation for the website, ultimately leading to increased sales and customer loyalty.

How to make curl request in Magento 2?

Give your Magento 2 module a boost with cURL capabilities! By injecting the Magento\Framework\HTTP\Client\Curl class via the constructor, you can create a reusable cURL client instance ($_curl).

Using this cURL instance, you can make quick and easy HTTP requests that can fetch dynamic data, integrate APIs, and increase your Magento 2 extension's connectivity. Unleash the power of cURL for efficient and reliable communication in your Magento 2 projects using following guide.

/**
* @var \Magento\Framework\HTTP\Client\Curl
*/
private $_curl;

/**
* Class Constructor.
*
* @param Magento\Framework\HTTP\Client\Curl $curl
*/
public function __construct(
   Magento\Framework\HTTP\Client\Curl $curl
) {
   $this->_curl = $curl;
}

Make a GET request call using cURL

Magento 2's cURL capabilities can be easily harnessed with a simple GET request, using the '$curl' object. Simply specify the endpoint URL through the '$url' variable, and initiate the GET method.

The result, including the response body, can then be retrieved through 'getBody()', allowing you to conveniently fetch data from APIs or external services, opening up greater possibilities for your Magento 2 applications.

// cURL GET method call using $url variable as endpoint URL.
$this->_curl->get($url);

// response body of curl request
$result = $this->_curl->getBody();

Make a POST request call using cURL

In the example below,

  • $url is the endpoint URL.
  • $params is an array of data sent via the POST request.

Here is an example of the $params variable:

This cURL example demonstrates how to send a POST request using an '_curl' object. An array ('$params') is used to pass data in the POST body, which is sent to a specific URL endpoint.

The 'getBody' method captures the response body, providing developers access to the server's response. This post method is essential for interacting with APIs and dynamic web content such as form submissions.

$params = [
  'form[email]' => $form['email'],
  'form[telephone]' => $form['telephone'],
  'form[city]' => $form['city'],
]
// cUrl post method call uses $url variable as endpoint URL and params as POST variables.
$this->_curl->post($url, $params);

// response body of curl request
$result = $this->_curl->getBody();

Set the cURL header using the addHeader method

Note: You need to set up the headers in cURL before start using the HTTP Methods.

$this->_curl->addHeader("Content-Type", "application/json");
$this->_curl->addHeader("Content-Length", 200);

Set the cURL array header using setHeaders method

The setHeaders method accepts one parameter as an array.

$headers = ["Content-Type" => "application/json", "Content-Length" => "200"];
$this->_curl->setHeaders($headers);

Set basic username and password authorization in cURL

Set the basic authorization using setCredentials().

php
$username = "username";
$password = "password";

$this->_curl->setCredentials($username, $password);

// You can also set up the basic authorization via addHeader.
$this->_curl->addHeader("Authorization", "Basic " . base64_encode($userName . ":" . $password));

Set the cURL option using set Option method

setOption() takes two parameters. The option name and option value of the cURL.

$this->_curl->setOption(CURLOPT_RETURNTRANSFER, true);

// OR 

$options = [CURLOPT_RETURNTRANSFER => true, CURLOPT_PORT => 8081];
$this->_curl->setOptions($options);

Set cURL cookies using the addCookie or setCookies method

The addCookie() function takes two arguments. The first parameter is the cookie name, and the second is the cookie value.

addCookie define single value as key and value option for set cookies for cURL request.

php
class="western">
$this->curl->addCookie("cookie-days","100");

$this->curl->addCookie("cookie-name", "Custom_Cookie");

setCookies is used to define multiple cookies at the same time for cURL requests.

class="western">
$cookies=["cookie-days"=>"100","cookie-name"=>"Custom_Cookie"];

$this->curl->setCookies($cookies);
php
$this->_curl->addCookie("cookie-name", "cookie-value");

$cookies = ["cookie-1" => "value-1", "cookie-2" => "value-2"];
$this->_curl->setCookies($cookies);

Conclusion:

Magento 2 development cURL shows up as smooth connectivity and dynamic data integration. From simple GET requests to handling complex transactions, cURL's versatility shines through. With its capacity to support various protocols and APIs, Magento 2 development cURL provides developers with a powerful tool for secure data exchange. Its flexibility allows for the reliable handling of data transfers, making it essential to creating robust and dynamic e-commerce solutions.

The Elightwalk team is an expert in Magento 2 development and can provide customized solutions tailored to your firm's needs. Hire the best team for your e-commerce project and make it a success.

FAQs about Curl requests in Magento 2

Why am I receiving cURL error code 6, "Couldn't resolve host"?

What does cURL error code 7 signify?

How should I address cURL error code 28, "Connection timed out"?

Why am I facing cURL error code 60?

How can I resolve cURL error code 403, "Forbidden"?

Pravin Prajapati
Full Stack Developer

Expert in frontend and backend development, combining creativity with sharp technical knowledge. Passionate about keeping up with industry trends, he implements cutting-edge technologies, showcasing strong problem-solving skills and attention to detail in crafting innovative solutions.

Most Visited Blog

The Ultimate Guide to Creating the Best Grid in Magento of 2022

Dive into the guide to creating an excellent Magento grid in 2022. Discover professional insights, strategies, and tactics for improving the grid design and functioning of an e-commerce platform for a better user experience.

How to add customer total order in the column customer grid in Magento 2?

Improve your client management with Magento 2! Learn how to add the order value to customer grid column step by step. Improve visibility and consumer insights for informed and efficient shopping experience.

New Email Sender Requirements from Gmail & Yahoo: What You Should Know

Keep up to date on the most recent email sender criteria from Gmail and Yahoo. Learn how to protect your emails, increase deliver ability, and avoid potential problems.