How do I make a post request with curl without using a button, but instead calling the external API when a field is filled out

3 Answers 3


If you are working within Magento Try to use magento logic where possible rather than native php functions

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

 * @param Context                             $context
 * @param \Magento\Framework\HTTP\Client\Curl $curl
public function __construct(
    Context $context,
    \Magento\Framework\HTTP\Client\Curl $curl
) {
    $this->_curl = $curl;

public function execute()
    //if the method is get
    //if the method is post
    $this->_curl->post($url, $params);
    //response will contain the output in form of JSON string
    $response = $this->_curl->getBody();

More can be found here


  1. Determine the API endpoint: Identify the URL of the API endpoint that you want to call.

  2. Initialize cURL: In your Magento 2 code, you can initialize cURL by creating a new cURL handle with curl_init(). For example:

     $curl = curl_init();
  3. Set the cURL options: Set the cURL options that you need for your API call. For example, you may need to set the URL, the request method, and any headers or parameters. Here's an example:

         curl_setopt_array($curl, array(
             CURLOPT_URL => "https://api.example.com/endpoint",
             CURLOPT_RETURNTRANSFER => true,
             CURLOPT_ENCODING => "",
             CURLOPT_MAXREDIRS => 10,
             CURLOPT_TIMEOUT => 30,
             CURLOPT_POSTFIELDS => "param1=value1&param2=value2",
             CURLOPT_HTTPHEADER => array(
                 "Content-Type: application/x-www-form-urlencoded",
                 "Authorization: Bearer my_token"

In this example, the cURL options include the API endpoint URL, the request method (POST), the request parameters, and the Authorization header with a bearer token.

  1. Execute the cURL request: Use the curl_exec() function to execute the cURL request. For example:

     $response = curl_exec($curl);

This will execute the cURL request and store the response in the $response variable.

  1. Handle the response: You can then handle the response from the API as needed. For example, you may need to parse the JSON data in the response or check for errors.

  2. Close the cURL handle: Finally, close the cURL handle with curl_close(). For example:


You need to create a custom controller and post data in that through ajax, then use curl in the controller:

  $buffer = curl_exec($curl_handle);
  if (empty($buffer)){
      print "Nothing returned from url.<p>";
      print $buffer;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.