Search code examples
javascriptgoogle-translategoogle-translation-api

What argument should i put in google translate api request body?


try {
const response = await fetch(googleTranslateApi + apiKey, {
    method: 'POST',
    headers: {
           Accept: 'application/json',
           'Content-Type': 'application/json',
           charset: 'UTF-8',

     },
    body: JSON.stringify({
        requests: [
          {
            q: 'Hello My Friend',
            target: 'zh',

           }

          ]
    })
});
const responseJson = await response.json();

I'm trying to call the google translate API, but I keep getting this error:

error: {code: 400, message: "Missing required field target", errors: Array(1), status: "INVALID_ARGUMENT"}

what am I missing from the request body?


Solution

  • I believe you have the right data in your request body, just formatted incorrectly. You have the q and target properties nested inside an object that's inside an array that's inside your top-level request body object. Instead, put the q and target properties directly inside your top-level request body object, like this:

    try {
    const response = await fetch(googleTranslateApi + apiKey, {
        method: 'POST',
        headers: {
               Accept: 'application/json',
               'Content-Type': 'application/json',
               charset: 'UTF-8',
    
         },
        body: JSON.stringify({
          q: 'Hello My Friend',
          target: 'zh'
        })
    });
    const responseJson = await response.json();