Search code examples
authenticationibm-cloudnode-modulesibm-watsonibm-iam

IBM IAM IamAuthenticator getToken is not a function


I'm trying to get a token to use IBM Watson Speech-to-Text in my app. Here's my code:

const { IamAuthenticator } = require('ibm-cloud-sdk-core');

const authenticator = new IamAuthenticator({
    apikey: 'myApiKey',
  });

  authenticator.getToken(function (err, token) {
    if (!token) {
      console.log('error: ', err);
    } else {
      // use token
    }
  });

The error message is authenticator.getToken is not a function.

The documentation says:

string IBM.Cloud.SDK.Core.Authentication.Iam.IamAuthenticator.GetToken  (       )   

I've tried both getToken and GetToken. Same error message. The code isn't complicated, what am I doing wrong?


Solution

  • This is what worked for me with the latest ibm-watson node-sdk,

    Install node-sdk with this command

    npm install --save ibm-watson
    

    Then, use this code snippet in your app.js or server.js node file to receive the IAM access token

    const watson = require('ibm-watson/sdk');
    const { IamAuthenticator } = require('ibm-watson/auth');
    
    // to get an IAM Access Token
    const authorization = new watson.AuthorizationV1({
      authenticator: new IamAuthenticator({ apikey: '<apikey>' }),
      url: ''
    });
    
    authorization.getToken(function (err, token) {
      if (!token) {
        console.log('error: ', err);
      } else {
        console.log('token: ', token);
      }
    });
    

    You can also directly use the IamAuthenticator with Speech to Text

    const fs = require('fs');
    const SpeechToTextV1 = require('ibm-watson/speech-to-text/v1');
    const { IamAuthenticator } = require('ibm-watson/auth');
    
    const speechToText = new SpeechToTextV1({
      authenticator: new IamAuthenticator({ apikey: '<apikey>' }),
      url: 'https://stream.watsonplatform.net/speech-to-text/api/'
    });
    
    const params = {
      // From file
      audio: fs.createReadStream('./resources/speech.wav'),
      contentType: 'audio/l16; rate=44100'
    };
    
    speechToText.recognize(params)
      .then(response => {
        console.log(JSON.stringify(response.result, null, 2));
      })
      .catch(err => {
        console.log(err);
      });
    
    // or streaming
    fs.createReadStream('./resources/speech.wav')
      .pipe(speechToText.recognizeUsingWebSocket({ contentType: 'audio/l16; rate=44100' }))
      .pipe(fs.createWriteStream('./transcription.txt'));