Watson api using node.js

I am trying to use this node.js code to use the watson api which is in the cloud bluemix ibm in our ios application. Can someone tell me what this code is doing and give us an answer on how to use the watson service from our application.

var express = require('express'); var https = require('https'); var url = require('url'); // setup middleware var app = express(); app.use(express.errorHandler()); app.use(express.urlencoded()); // to support URL-encoded bodies app.use(app.router); app.use(express.static(__dirname + '/public')); //setup static public directory app.set('view engine', 'jade'); app.set('views', __dirname + '/views'); //optional since express defaults to CWD/views // There are many useful environment variables available in process.env. // VCAP_APPLICATION contains useful information about a deployed application. var appInfo = JSON.parse(process.env.VCAP_APPLICATION || "{}"); // TODO: Get application information and use it in your app. // defaults for dev outside bluemix var service_url = '<service_url>'; var service_username = '<service_username>'; var service_password = '<service_password>'; // VCAP_SERVICES contains all the credentials of services bound to // this application. For details of its content, please refer to // the document or sample of each service. if (process.env.VCAP_SERVICES) { console.log('Parsing VCAP_SERVICES'); var services = JSON.parse(process.env.VCAP_SERVICES); //service name, check the VCAP_SERVICES in bluemix to get the name of the services you have var service_name = 'question_and_answer'; if (services[service_name]) { var svc = services[service_name][0].credentials; service_url = svc.url; service_username = svc.username; service_password = svc.password; } else { console.log('The service '+service_name+' is not in the VCAP_SERVICES, did you forget to bind it?'); } } else { console.log('No VCAP_SERVICES found in ENV, using defaults for local development'); } console.log('service_url = ' + service_url); console.log('service_username = ' + service_username); console.log('service_password = ' + new Array(service_password.length).join("X")); var auth = "Basic " + new Buffer(service_username + ":" + service_password).toString("base64"); // render index page app.get('/', function(req, res){ res.render('index'); }); // Handle the form POST containing the question to ask Watson and reply with the answer app.post('/', function(req, res){ // Select healthcare as endpoint var parts = url.parse(service_url +'/v1/question/healthcare'); // create the request options to POST our question to Watson var options = { host: parts.hostname, port: parts.port, path: parts.pathname, method: 'POST', headers: { 'Content-Type' :'application/json', 'Accept':'application/json', 'X-synctimeout' : '30', 'Authorization' : auth } }; // Create a request to POST to Watson var watson_req = https.request(options, function(result) { result.setEncoding('utf-8'); var response_string = ''; result.on('data', function(chunk) { response_string += chunk; }); result.on('end', function() { var answers_pipeline = JSON.parse(response_string), answers = answers_pipeline[0]; return res.render('index',{'questionText': req.body.questionText, 'answers': answers}) }) }); watson_req.on('error', function(e) { return res.render('index', {'error': e.message}) }); // create the question to Watson var questionData = { 'question': { 'evidenceRequest': { 'items': 5 // the number of anwers }, 'questionText': req.body.questionText // the question } }; // Set the POST body and send to Watson watson_req.write(JSON.stringify(questionData)); watson_req.end(); }); // The IP address of the Cloud Foundry DEA (Droplet Execution Agent) that hosts this application: var host = (process.env.VCAP_APP_HOST || 'localhost'); // The port on the DEA for communication with the application: var port = (process.env.VCAP_APP_PORT || 3000); // Start server app.listen(port, host); 
+6
source share
2 answers

Most of this code is required for Node and for execution in BlueMix. VCAP_SERVICES is the Bluemix environment variable that you use to obtain the credentials for this service that you are interested in using. In this case, the service_name parameter is set to question_and_answer to access the Q&A platform service.

In your Bluemix environment, you must have a Q & A instance and application. When an application is bound to a Q & A service, it creates a binding to the service. The service binding has application credentials for accessing the service instance. In this case, VCAP_SERVICES contains the URL, username and password of the binding used to transmit and authenticate with the service instance.

From your iOS application you will need a few things. First, you need a service binding, and for now, you need to create this in Bluemix. Once you have your credentials in Bluemix, you can use them in your iOS app. Or you can host the app on Bluemix and let it interact with Watson.

Then you need the ability to call the Question and Answer service, which is a RESTful service. In the above code, the options variable contains the necessary information for a POST question to the Watson service. Please note that the service_url obtained from the credentials is added with additional information about the path to use the Watson For Healthcare domain.

From there you can create your own question. The questionData variable contains the question in the code above. The question.questionText property has been asked a question that you want to ask Watson, for example: "Do I have to take aspirin on a daily basis?"

You can then submit the question to Watson, as the following snippet does:

 watson_req.write(JSON.stringify(questionData)); 

Node is asynchronous, so the response is processed in http.request(...) . The response is sent back to the requesting application at

 result.on('end', function() { var answers_pipeline = JSON.parse(response_string), answers = answers_pipeline[0]; return res.render('index',{'questionText': req.body.questionText, 'answers': answers}) }) 

The rest of the code is Node. But I outlined the basics you need in an iOS app.

+6
source

All code is designed to handle an HTTPS request for the Watson Question and Answer service .

If you want to use this service in your IOs application, you need to:

  • Modify the nodejs code and add the features of the REST API.

    For example, you should have an endpoint for questions and answers:

     app.get('/api/question', function(req, res){ // Call the service with a question and get an array with the answers var answers = watson.question(req.query); // Send the answers and the question to the client in json res.json({answers: answers, question: req.query.question}); }); 
  • Run the application in bluemix and save the url, it will be something like:

      http://my-cool-app.mybluemix.net 
  • Call your API at http://my-cool-app.mybluemix.net/api/question?question=Watson

Notes:

For the IOs application, you can use AFNetworking .

You should also read the Q&A service documentation message here and read about the service API here.

+3
source

Source: https://habr.com/ru/post/977530/


All Articles