Search code examples
google-translategoogle-translation-api

how to pass format to google cloud translation API using the client library?


We are using google cloud translation API in our express application. I am trying to do translations using the client library instead of making an API request every time. 1. What I want to know is how to pass the options like format (text or html) to the api while using the client library? I can achieve this via making http requests using requestjs like this:

var request = require('request');
var url = 'https://translation.googleapis.com/language/translate/v2';
var options1 = {
  q: 'amore mio',
  target: 'hi',
  format: 'text',
  source: 'it',
  key: 'my API key'
}

request.post({url:url, qs:options1}, (err, res, body)=> {
  if(err) {
    console.log('ERR: ', err);
  }
  console.log('RES: ', res.statusCode);
  console.log('Body: ', body);
})

But the sample for using client library shows only this:

const {Translate} = require('@google-cloud/translate');

// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Instantiates a client
const translate = new Translate({
  projectId: projectId,
});

// The text to translate
const text = 'Hello, world!';
// The target language
const target = 'ru';

// Translates some text into Russian
translate
  .translate(text, target)
  .then(results => {
    const translation = results[0];

console.log(`Text: ${text}`);
console.log(`Translation: ${translation}`);


})
.catch(err => {
        console.error('ERROR:', err);
 });

Is there a way I can pass options like 'format' using the client library?

  1. How can I pass an array of strings to the q attribute (querystring) of the options object in the first method? If I pass an array directly like:

    q: ['amore mio', 'grazie']

I get an error message :

RES:  400
Body:  {
  "error": {
    "code": 400,
    "message": "Required Text",
    "errors": [
      {
        "message": "Required Text",
        "domain": "global",
        "reason": "required"
      }
    ]
  }
}

Solution

  • With respect to question 2 about passing the array of input arguments, this works fine if you use cURL to send the POST request similar to this example. I have tried it myself with success. I have tried to do different manipulations with your code from snipper 1 with the request library, but it seems as if the request library is not passing the array correctly. I would generally suggest using the client library which can successfully handle arrays in the input text.