CURL POST showing 400 error from php but working fine from shell command or CLI

Viewed 20

I am using Natural Language Understanding (NLU) which is from IBM Watson. For understanding : https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-getting-started

My Curl post working fine from CLI or shell command but not working when done using php.They are showing 400 error. Referance: https://www.ibm.com/support/pages/400-bad-request-request-or-response-invalid

curl -X POST -u "apikey:***my-api-key***" \
--header "Content-Type: application/json" \
--data '{
  "text": "I love apples! I do not like oranges.",
  "features": {
    "keywords": {
      "emotion": true
    }
  }
}' \
 "https://api.au-syd.natural-language-understanding.watson.cloud.ibm.com/instances/0623bfb1-a19a-456b-b3df-12a42434241de/v1/analyze?version=2019-07-12"

When I run the above command from CLI or shell than I get the appropiate result. But I want to get the result by making the curl from php. But I am getting 400:Bad request error. I think the error in on the array of the post $data. Here I am attaching my php code.

<?php
    
    /* API URL */
    $apikey = '***my-api-key***';
    $url = 'https://api.au-syd.natural-language-understanding.watson.cloud.ibm.com/instances/0623bfb1-a19a-456b-b3df-12a42434241de/v1/analyze?version=2019-07-12';
        
    /* Init cURL resource */
    $ch = curl_init($url);
        
    /* Array Parameter Data */
    $data = array('text'=>'I love apples! I do not like oranges',
              'features'=> array('keywords'=> array('emotion'=> 'true')));
    
        
    /* pass encoded JSON string to the POST fields */
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        
    /* set the content type json */
    $headers = [];
    $headers[] = 'Content-Type:application/json';
    curl_setopt($ch, CURLOPT_USERPWD, 'apikey:' . $apikey);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
    /* set return type json */
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
    /* execute request */
    $result = curl_exec($ch);
         
    //print_r($result);
    /* close cURL resource */
    $response = json_decode($result);

    print_r($response);
    curl_close($ch);
  
?>
0 Answers
Related