Reputation: 4590
I have successfully called the Watson Speech-To-Text API using the prescribed curl approach shown here. I used the child_process
node module to invoke Curl
from my node script.
I am trying to transition to using the request
module to perform the same network request (getting a json dump of the transcription). I'm having some trouble composing to proper http request in requests
's terms. So far, I have:
request({
url: 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true×tamps=true',
method: 'POST',
headers: {
'Content-Type': 'audio/wav',
'Transfer-Encoding':'chunked',
'Authorization': 'Basic <usernameRedacted:passwordRedacted>'
},
body: {
'--data-binary': audioFileName
}
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
I'm getting either throw new TypeError('first argument must be a string or Buffer');
or sometimes (after modifying the request call properly) a 400 http response code. So as I understand that Curl
is simply a Unix process running the same underlying Post request, presumably, I should be able to make this work. Unfortunately, I seem to be missing some critical fixes here. More over, NPM requests
README is unclear to me with regards to the authentication, and how I would load the binary data (--data-binary in CURL
) into the POST body.
Any help is greatly appreciated in advance.
Upvotes: 1
Views: 688
Reputation: 19428
You can stream any type of data directly into a request by using pipe()
since all requests are a Stream. Technically you don't need to add the Content-Type
header since request will figure it out based on the file extension being piped in but, if you explicitly pass it in, request will use the one set by you and not determine it automatically.
Also for authentication, request will take an auth
option with a username and password along with some other options. See the request
HTTP Auth Docs for specifics to how you need to get it working.
I've provided a sample of how to pipe data to a request and how to do a request with HTTP Basic Auth
const request = require('request');
const fs = require('fs');
fs.createReadStream(audioFileName)
.pipe(request({
uri: 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true×tamps=true',
method: 'POST',
auth: {
user: '',
pass: ''
},
headers: {
'Content-Type': 'audio/wav',
'Transfer-Encoding': 'chunked'
}
}, (err, res, body) => {
if (err)
console.log(err);
else
console.log(body);
}));
Upvotes: 2