Can't access IBM Tone Analyzer API?

孤街醉人 提交于 2021-01-27 04:27:29

问题


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.


回答1:


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!




回答2:


It's 401 status code which uses for unauthorized access, you need to login first before accessing the API.

I check the docs for this and here is the link, for login to the api before using it tone-analyzer#authentication

With some service instances, you authenticate to the API by using IAM. You can pass either a bearer token in an Authorization header or an API key. Tokens support authenticated requests without embedding service credentials in every call. API keys use basic authentication.



来源:https://stackoverflow.com/questions/55912989/cant-access-ibm-tone-analyzer-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!