Search code examples
laravelphp-curltone-analyzer

Can't access IBM Tone Analyzer API?


I'm trying to use the Tone Analyzer API in a Laravel application. No matter what I try, I always get the same response of {"code":401, "error": "Unauthorized"}. I suspect my issue is that I can't figure out how to pass in the API key, but the official documentation is no help whatsoever because it only contains instructions for using cURL in the command line. My code currently looks like this (though I have tried many many other iterations. If anyone needs me to I can post all the other unsuccessful attempts as well):

$response = Curl::to('https://gateway-wdc.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&sentences=false')
        ->withOption('HTTPHEADER', array(
            'Content-Type: application/json',
            'apikey: REDACTED'))
        ->withData(array('text' => $text))
        ->asJson()
        ->post();

I am running Laravel 5.8 and using Ixudra's cURL library. I would prefer if answers made use of this library too but honestly at this point I'm ready to give up and use vanilla PHP anyway so any answers are appreciated.

Ninja edit: I know the problem is not my account / API key, because I have tried to access the API through the command line and it worked just as expected. The issue only arises when trying to access it from Laravel.


Solution

  • IBM Watson Services uses HTTP Header Authentication in Basic format. Therefore, using curl in the terminal, you should pass the-u or --user flag in the format user:password, or you can also send the Authentication Http Header in pattern: Basic user:password.

    By adjusting your code for this second form, you can do it as follows:

    $response = Curl::to('https://gateway-wdc.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&sentences=false')
            ->withHeader('Content-Type: application/json')
            ->withHeader('Authorization: Basic apikey:YOUR_TOKEN_HERE')
            ->withData(array('text' => $text))
            ->asJson()
            ->post();
    

    Replace YOUR_TOKEN_HERE by your Tone Analyzer API access token.

    https://developer.mozilla.org/docs/Web/HTTP/Authentication https://www.ibm.com/support/knowledgecenter/en/SSGMCP_5.3.0/com.ibm.cics.ts.internet.doc/topics/dfhtl2a.html

    Hope this helps!