IBM Watson Personality Insights Service : giving bad request as response - node.js

I am using NodeJS SDK of watson to test Personality Insights Service but getting the following error:
> Error: { Bad Request: Invalid JSON input at line 1, column 2
> at RequestWrapper.formatError (C:\Users\...\Desktop\..\..\ibm-analyser-cloud\node_modules\ibm-cloud-sdk-core\lib\request-wrapper.js:208:21)
> at C:\Users\...\Desktop\..\..\ibm-analyser-cloud\node_modules\ibm-cloud-sdk-core\lib\request-wrapper.js:196:25
> at process._tickCallback (internal/process/next_tick.js:109:7) name: 'Bad Request', code: 400, message: 'Invalid JSON input at
> line 1, column 2', body:
> '{"code":400,"sub_code":"S00005","error":"Invalid JSON input at line
> 1, column 2"}', headers: { 'content-type': 'application/json',
> 'content-length': '81',
> 'access-control-allow-origin': '*',
> 'x-service-api-version': '4.0.2',
> 'x-service-build-number': '2020-01-20T06:02:53.029 UTC',
> 'x-content-type-options': 'nosniff',
> 'x-xss-protection': '1; mode=block',
> 'content-security-policy': 'default-src \'none\'',
> pragma: 'no-cache',
> 'cache-control': 'no-store',
> 'x-service-pi-error-code': 'S00005',
> 'content-language': 'en-US',
> 'strict-transport-security': 'max-age=31536000; includeSubDomains;',
> 'x-global-transaction-id': '833a39d917c511e8921aa5286669721c',
> 'x-dp-watson-tran-id': '833a39d917c511e8921aa5286669721c',
> 'x-edgeconnect-midmile-rtt': '289',
> 'x-edgeconnect-origin-mex-latency': '416',
> date: 'Tue, 28 Jan 2020 02:59:53 GMT',
> connection: 'close' } }
Below is the code snippet I am using :
app.get("/personality-insights", function(req, res) {
const personalityInsights = new PersonalityInsightsV3({
version: '2017-10-13',
authenticator: new IamAuthenticator({
apikey: watsonKeyPersonalityInsights,
}),
url: watsonUrlPersonalityInsights,
});
let params = {
content: "I am very happy today",
content_type: 'text/plain',
raw_scores: true,
consumption_preferences: true
};
personalityInsights.profile(params, function(error, response) {
if (error)
console.log('Error:', error);
else
console.log(JSON.stringify(response, null, 2));
}
);
});
this is a sample Node JS based snippet where I am providing the API credentials and the URL provided by the IBM cloud and making the request with a single line of input text. Everything seems correct but don't know why I am getting that error.

All the parameters were converted to lower camel case in v5. See the MIGRATION doc in the repo and the parameter details in the API reference
contentType
rawScores
consumptionPreferences

Related

PayPal 401 Client Authentication Failed in Sandbox environment with node js sdk

I've followed this guide https://developer.paypal.com/docs/checkout/reference/server-integration/setup-sdk/ and this example https://github.com/paypal/Checkout-Nodejs-SDK/
Here is my code:
import paypalCheckout from '#paypal/checkout-server-sdk';
const environment = new paypalCheckout.core.SandboxEnvironment(
'ACTUAL_CLIENT_ID_FROM_PAYPAL_DASHBOARD',
'ACTUAL_CLIENT_SECRET_FROM_PAYPAL_DASHBOARD'
);
const client = new paypalCheckout.core.PayPalHttpClient(environment);
const request = new paypalCheckout.orders.OrdersCreateRequest();
request.requestBody({
intent: 'CAPTURE',
purchase_units: [
{
amount: {
currency_code: 'USD',
value: `100.00`
}
}
],
});
client.execute(request)
.then((response) => {
console.log(`${JSON.stringify(response)}`);
console.log(`${JSON.stringify(response?.result)}`);
})
.catch((executeError) => {
console.log(`${JSON.stringify(executeError)}`);
});
I get:
{
error: HttpError: {"error":"invalid_client","error_description":"Client Authentication failed"}
at IncomingMessage.<anonymous> (.../node_modules/#paypal/paypalhttp/lib/paypalhttp/http_client.js:136:22)
at IncomingMessage.emit (events.js:388:22)
at endReadableNT (internal/streams/readable.js:1336:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
statusCode: 401,
headers: {
'content-type': 'application/json',
'content-length': '77',
connection: 'close',
date: 'Tue, 29 Jun 2021 01:22:38 GMT',
'cache-control': 'max-age=0, no-cache, no-store, must-revalidate',
'paypal-debug-id': 'c2b.......c7a',
'x-paypal-token-service': 'IAAS',
'strict-transport-security': 'max-age=31536000; includeSubDomains'
},
_originalError: {
text: '{"error":"invalid_client","error_description":"Client Authentication failed"}',
statusCode: 401,
headers: [Object]
}
},
message: '{"error":"invalid_client","error_description":"Client Authentication failed"}'
}
I've searched Google and Stack Overflow but I only find similar issues about switching from sandbox to live.
My code isn't working in sandbox environment.

I have followed the api documentation for Watson Tone analyser to no avail - can't connect the two endpoints

I have a Watson Tone cloud service up and running and I am trying to link it to my index.js file. However it doesn't seem to want to connect.
Code below:
const ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3');
const toneAnalyzer = new ToneAnalyzerV3({
version: '2017-09-21',
iam_apikey: 'omoNirDx1MUQwCdlHTQ-5Fxklx2_c0dUVAyMFIItFLty',
url: 'http://watson-row-analyser.eu-gb.cf.appdomain.cloud/#'
});
const text =
'Team, I know that times are tough! Product ' +
'sales have been disappointing for the past three ' +
'quarters. We have a competitive product, but we ' +
'need to do a better job of selling it!';
const toneParams = {
tone_input: { text: text },
content_type: 'application/json'
};
toneAnalyzer
.tone(toneParams)
.then((toneAnalysis) => {
console.log(JSON.stringify(toneAnalysis, null, 2));
})
.catch((err) => {
console.log('error:', err);
});
Current error code:
Marcs-MacBook-Pro:npm-global marcwatts$ node index1.js
error: { Not Found: Not Found
at formatError (/Users/marcwatts/Desktop/mxw817/DBTestApp/npm-global/node_modules/watson-developer-cloud/node_modules/ibm-cloud-sdk-core/lib/requestwrapper.js:111:17)
at /Users/marcwatts/Desktop/mxw817/DBTestApp/npm-global/node_modules/watson-developer-cloud/node_modules/ibm-cloud-sdk-core/lib/requestwrapper.js:259:19
at process._tickCallback (internal/process/next_tick.js:68:7)
name: 'Not Found',
code: 404,
message: 'Not Found',
body:
'"<!DOCTYPE html>\\n<html lang=\\"en\\">\\n<head>\\n<meta charset=\\"utf-8\\">\\n<title>Error</title>\\n</head>\\n<body>\\n<pre>Cannot POST /</pre>\\n</body>\\n</html>\\n"',
headers:
{ 'x-backside-transport': 'FAIL FAIL',
connection: 'close',
'transfer-encoding': 'chunked',
'content-security-policy': 'default-src \'none\'',
'content-type': 'text/html; charset=utf-8',
date: 'Sat, 06 Jul 2019 15:32:34 GMT',
'x-content-type-options': 'nosniff',
'x-powered-by': 'Express',
'x-global-transaction-id': 'ba9308f85d20bf12a70673ff' } }
Link to api for Watson:
https://cloud.ibm.com/apidocs/tone-analyzer?code=node
Code 404 means Not Found. A requested item or parameter does not exist. What am I missing?

the problem of unauthorized in IBM watson assistant Nodejs

I tried the API v1 and v2 of IBM Watson assistant to creat a new conversion.
But it gived me always the samr error code 401 Unauthorized: Access is denied due to invalid credentials.
i don't know what happened, thanks in advance for your answers.
{ Unauthorized: Access is denied due to invalid credentials.
at RequestWrapper.formatError (E:\Documents\Techniques\Desktop\front_back_end\version-watson\node_modules\ibm-watson\node_modules\ibm-cloud-sdk-core\lib\requestwrapper.js:218:21)
at E:\Documents\Techniques\Desktop\front_back_end\version-watson\node_modules\ibm-watson\node_modules\ibm-cloud-sdk-core\lib\requestwrapper.js:206:29
at process._tickCallback (internal/process/next_tick.js:68:7)
name: 'Unauthorized',
code: 401,
message: 'Access is denied due to invalid credentials.',
body: '{"code":401,"error":"Unauthorized"}',
headers:
{ 'x-backside-transport': 'FAIL FAIL',
'content-type': 'application/json',
'x-dp-transit-id': 'gateway01-1474836587',
'x-global-transaction-id': '7ecac92c5d14b5ae57e8386b',
'strict-transport-security': 'max-age=31536000;',
'x-dp-watson-tran-id': 'gateway01-1474836587',
'content-length': '37',
'x-edgeconnect-midmile-rtt': '82',
'x-edgeconnect-origin-mex-latency': '110',
date: 'Thu, 27 Jun 2019 12:25:18 GMT',
connection: 'close' } }
const AssistantV1 = require('ibm-watson/assistant/v1');
const service = new AssistantV1({
version: '2019-02-28',
iam_apikey: '{apikey}',
url: '{url}'
});
service.message({
workspace_id: '{workspace_id}',
input: {'text': 'Hello'}
})
.then(res => {
console.log(JSON.stringify(res, null, 2));
})
.catch(err => {
console.log(err)
});
I am not sur that for Version2 the session-id is correct or not. But the API v1 doesn't need the session_id, it gives the same error code too.

how to read data from apiResponse in Nodejs typescript?

I want to read data from a googleapis call. I am using async-await. But I am not sure how to read the data that I am getting back.
async function makeCall(params:String){
const apiResponse = await goopleapi.particular.get(params);
console.log(`not really sure how to read -- ${apiResponse}`;
// problem is the log prints [object Object].
}
How do I get the log from printing [object Object] to the actual content of the response? Ultimately I want to read the json that comes back -- how do I do that? Thanks.
In case it's important. I am using Firebase as a back-end with Typescript
udpate 1
The api in question is for billing. As in https://www.googleapis.com/auth/androidpublisher. I am calling .purchases.products.get. And when I try to parse the response with JSON.parse(apiResponse), I get the error:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at getItem (/srv/lib/index.js:31:69)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:145:8)
documentation: https://developers.google.com/android-publisher/api-ref/purchases/products/get
update 2
Here is the apiResponse that I need to parse into json. I tried using JSON.parse(apiResponse) but got an error:
{ config:
{ url: 'https://www.googleapis.com/androidpublisher/v2/applications/mypath',
method: 'GET',
paramsSerializer: [Function],
headers:
{ 'Accept-Encoding': 'gzip',
'User-Agent': 'google-api-nodejs-client/2.0.0 (gzip)',
Authorization: 'Bearer somecode',
Accept: 'application/json' },
params: {},
validateStatus: [Function],
retry: true,
responseType: 'json' },
data:
{ kind: 'androidpublisher#productPurchase',
purchaseTimeMillis: '111222333',
purchaseState: 0,
consumptionState: 1,
developerPayload: '',
orderId: 'some string',
purchaseType: 0 },
headers:
{ 'alt-svc': 'quic=":111"; ma=33445566; v="a string"',
'cache-control': 'private, max-age=0, must-revalidate, no-transform',
connection: 'close',
'content-encoding': 'gzip',
'content-type': 'application/json; charset=UTF-8',
date: 'Fri, 14 Jun 2019 12:40:12 GMT',
etag: '"some string"',
expires: 'Fri, 14 Jun 2019 12:40:12 GMT',
server: 'GSE',
'transfer-encoding': 'chunked',
vary: 'Origin, X-Origin',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '1; mode=block' },
status: 200,
statusText: 'OK' }
The error is still the same as in "update 1"
Template strings will call toString on the parts. You need to do
console.log('You need to pass it as a parameter', apiResponse)
If you want to print the actual object to the console.
The object has already been parsed. The error is from passing json to JSON.parse() which expects a string.
[object Object] is returned from the objects toString() method in a template literal, to avoid this:
console.log('Some string',apiResponse);
if theres still a problem try console.log(JSON.stringify(apiResponse))

How to find api-key and password for ibm-watson for Watson Assistant API working with nodejs

I'm trying to access my assistant but I'm getting a 404 Not Found error when inserting the iam_api_key and the url provided in the dahsboard.
And I can't find the password in the dahsboard.
I'm working with Node.js. I've tried to create other service credentials but nothing worked
{
username: '{api-key}',
password: '{password}', // I can't find this
// OR even
iam_apikey: '{api-key}'
url: '{url}',
version: '{version}',
disable_ssl_verification: true,
}
{ Not Found: Resource not found
{ ... }
at
at process._tickCallback (internal/process/next_tick.js:188:7) name: 'Not Found', code: 404, message: 'Resource not found',
body: '{"error":"Resource not found","code":404}', headers: {
'x-backside-transport': 'FAIL FAIL',
'content-type': 'application/json; charset=utf-8',
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS',
'access-control-allow-headers': 'Content-Type, Content-Length, Authorization, X-Watson-Authorization-Token, X-WDC-PL-OPT-OUT,
X-Watson-UserInfo, X-Watson-Learning-Opt-Out, X-Watson-Metadata',
'access-control-max-age': '3600',
'content-security-policy': 'default-src \'none\'',
'x-dns-prefetch-control': 'off',
'x-frame-options': 'SAMEORIGIN',
'strict-transport-security': 'max-age=31536000;',
'x-download-options': 'noopen',
'x-content-type-options': 'nosniff',
'x-xss-protection': '1; mode=block',
'x-global-transaction-id': '{x-global-transaction-id}',
'x-dp-watson-tran-id': '{x-dp-watson-tran-id}',
'x-dp-transit-id': '{x-dp-transit-id}',
'content-length': '41',
'x-edgeconnect-midmile-rtt': '124',
'x-edgeconnect-origin-mex-latency': '142',
date: 'Wed, 19 Jun 2019 20:38:08 GMT',
connection: 'close' } }
You have to use either the api key OR the username / password combination. The API docs for IBM Watson Assistant have code samples for Node.js:
const AssistantV2 = require('ibm-watson/assistant/v2');
const assistant = new AssistantV2({
version: '{version}',
iam_apikey: '{apikey}',
url: '{url}'
});
Use this code as well. It's working on me. I added serviceUrl and headers. Make sure to add the correct service URL according to the assistant URL.
const assistant = new AssistantV2({
version: "2019-02-28",
authenticator: authenticator,
url: process.env.WATSON_ASSISTANT_URL,
serviceUrl: "https://api.us-south.assistant.watson.cloud.ibm.com",
headers: {
"X-Watson-Learning-Opt-Out": "true",
},
});
Refer more - https://cloud.ibm.com/apidocs/assistant-v2?code=node#endpoint-cloud

Resources