John Davidson

Accessing IBM Tone Analyzer with PHP and CURL

0 comments
Message:


I would like to access IBM Tone Analyzer through PHP using CURL, however, I keep getting authorization errors like shown below. The code I use is shown in the code section.


Although looking up numerous help pages and forums, I haven't found a suitable solution. Could someone please help me how to solve this?


Thanks a lot in advance.


With best regards!


This is the code i use:




<?php

//print_r($_POST);

$ch = curl_init();

$file_path = "tone.json";
$url = "https://api.eu-gb.tone-analyzer.watson.cloud.ibm.com/instances/$BLACKENED$/v3/tone?$

$header_args = array(
'Accept: application/json',
'Content-Type: application/json',
'Authorization: Basic apikey:$BLACKENED$'
);

curl_setopt_array($ch,array(CURLOPT_URL => $url, CURLOPT_HEADER => $header_args, CURLOPT_UPLOAD => true, CURLOPT_POST => true, CURLOPT_INFILE => $file_path));

$response = curl_exec($ch);

echo($response);

curl_close($ch);

?>


My Answer:
It looks like you are trying to access the IBM Tone Analyzer API using a POST request with a JSON file. The issue might be with the way you are setting the Authorization header in your CURL request.

Instead of setting the Authorization header as:

'Authorization: Basic apikey:$BLACKENED$'

You should set it as:

'Authorization: apikey $BLACKENED$'

Here is the updated code:

php

$ch = curl_init();

$file_path = "tone.json";
$url = "https://api.eu-gb.tone-analyzer.watson.cloud.ibm.com/instances/$BLACKENED$/v3/tone";

$header_args = array(
'Accept: application/json',
'Content-Type: application/json',
'Authorization: apikey $BLACKENED$'
);

curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $header_args,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => file_get_contents($file_path),
));

$response = curl_exec($ch);

echo $response;

curl_close($ch);

?>


Make sure to replace `$BLACKENED$` with your actual API key. Also, I have changed the way you set the headers and the way you send the JSON file in the request. This should hopefully resolve the authorization issue you are facing. Let me know if you need further assistance.

Rate this post

4 of 5 based on 6997 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us