Search code examples
node.jsibm-cloudibm-watsonretrieve-and-rank

How to call API that requires user name and password, in Node.js


I am working with Retrieve and Rank service of IBM Watson. This service provides a REST API that returns search result. Following is the API URL

https://username:password@gateway.watsonplatform.net/retrieve-and-rank/api/v1/solr_clusters/sc6e46e4f5_f30c_4a8a_ae9c_b4ab6914f7b4/solr/example-collection/select?q=some question&wt=json&fl=id,title,body

As yo can notice this URL takes in a user name and a password. The Retreive and Rank documentation mentions the above pattern for calling the API, i.e, with user name and password as part of the URL. If I paste this in google chrome, it comes out with dialog box to enter user name and password again. After I enter the credentials I can see the data.

My question is, how do I call such a URL through Node.js. I do not know where do I start and what steps I should follow.


Solution

  • API of Retrieve and Rank service of IBM Watson uses basic authentication. Ways are several, one of them - use the module request:

    var url = "https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/solr_clusters/sc1ca23733_faa8_49ce_b3b6_dc3e193264c6/solr/example_collection/select?q=what%20is%20the%20basic%20mechanism%20of%20the%20transonic%20aileron%20buzz&wt=json&fl=id,title"
    
    request.get('http://some.server.com/', {
      auth: {
        user: 'username',
        pass: 'password',
        sendImmediately: false
      },
      json: true
    }, function(error, response, body) {
         console.log( 'Found: ', body.response.numFound );
    });
    

    or

    var username = 'username',
        password = 'password',
        url = "https://" + user + ":" + password + "@" + "gateway.watsonplatform.net/retrieve-and-rank/api/v1/solr_clusters/sc1ca23733_faa8_49ce_b3b6_dc3e193264c6/solr/example_collection/select?q=what%20is%20the%20basic%20mechanism%20of%20the%20transonic%20aileron%20buzz&wt=json&fl=id,title"
    
    request({url: url, json: true}, function (error, response, body) {
       console.log( 'Found: ', body.response.numFound );
    });