Google Translate API Tutorial for PHP / Javascript / Java

In Google Translate API Tutorial, I have explained how to convert text from one language to another using Google Translate API in PHP / JavaScript / Java.
Translate API has daily limit of 2 Million characters per day. You can increase the limit in the cloud console up to 50 Millions characters per day.They charge 20$ for 1 Million characters. Check this URL for Pricing Details.

Topics covered in this article
1) Get Google Translate API Key
2) List of Google Translate API
3) Google Translate API PHP Example.
4) Google Translate API Java Example.
5) Google Translate API Javascript Example.

 

1). How to Get Google Translate API Key.

To use the API you need get a Google API key;
a). Go to Cloud Console
b). Create a Project and select it.
c). On the left side bar, Go to “APIs & auth” Tab => APIs Tab
d). Enable “Translate API”
e). Go to “Credentials” Tab
f). Click on “CREATE NEW KEY”
g). Create “Server Key” for PHP / Java / Ruby / Python. Create “Browser Key” for JavaScript.

NewProject   Enable Google Translate API Credentials Create New Key

Check this page, how to get Google API key

 

2). List of Google Translate API

Google Provided REST API, so you can use them in any language.

You can pass below parameters to Translate API.

a).callback  -> this is for JavaScript. callback is invoked the when the translation is successful.
b).key  -> Google API key, without this you are not allowed to use this API.
c).source -> Source language
d).target  -> Destination language.
e).prettyprint  -> If it set to true, response will be readable format. Default is true
f).q -> Text to be translated.
Below is the list of API.
2.1) translate – You can use this API  to translate text from source language to destination language

You need to send GET request in the below format.

https://www.googleapis.com/language/translate/v2?key={YOUR_API_KEY}&source=en&target=de&q=Hello%20Ravi

Response from API :

{
 "data": {
  "translations": [
   {
    "translatedText": "Hallo Ravi"
   }
  ]
 }
}

You can request multiple translations in single request. You can do this by sending multiple ‘q’ parameters.
Sample GET request:

https://www.googleapis.com/language/translate/v2?key={YOUR_API_KEY}&source=en&target=de&q=Hello%20Ravi&q=How%20are%20you&q=I%20am%20fine

Response format:

{
 "data": {
  "translations": [
   {
    "translatedText": "Hallo Ravi"
   },
   {
    "translatedText": "Wie geht es Ihnen"
   },
   {
    "translatedText": "Mir geht es gut"
   }
  ]
 }
}

2.2) detect – You can use this API to detect the language of given text.

Sample GET Request:

https://www.googleapis.com/language/translate/v2/detect?key={YOUR_API_KEY}&q=Wie%20geht%20es%20Ihnen

Response:

{
 "data": {
  "detections": [
   [
    {
     "language": "de",
     "isReliable": false,
     "confidence": 1.0
    }
   ]
  ]
 }
}

2.3). languages – This API Lists the Source and Destination languages supported by the translate method

Sample GET Request:

https://www.googleapis.com/language/translate/v2/languages?key={YOUR_API_KEY}&target=de

 

How to handle Errors ? :

If there is any error in the URL request, you will get the error in the below formats.
ERROR 1:  Response when the key is invalid

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "keyInvalid",
    "message": "Bad Request"
   }
  ],
  "code": 400,
  "message": "Bad Request"
 }
}

ERROR 2: Response when target parameter is missing.

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required parameter: target",
    "locationType": "parameter",
    "location": "target"
   }
  ],
  "code": 400,
  "message": "Required parameter: target"
 }
}

 

3) Google Translate API PHP Example.

To use Google Translate API in PHP, you need to get Google API “Server Key”. All the translate API are called using GET requests. So we can use file_get_contents() or PHP CURL Library.To encode the parameter, rawurlencode() function is used. To decode JSON text as object, json_decode() function is used.

Google Translate API in PHP
I have given two examples, you can use any of these two examples.

Using CURL library:

<?php
$api_key = 'PUT_YOUR_SERVER_KEY_HERE';
$text = 'How are you';
$source="en";
$target="fr";

$obj = translate($api_key,$text,$target,$source);
if($obj != null)
{
	if(isset($obj['error']))
	{
		echo "Error is : ".$obj['error']['message'];
	}
	else
	{
		echo "Translsated Text: ".$obj['data']['translations'][0]['translatedText']."n";
		if(isset($obj['data']['translations'][0]['detectedSourceLanguage'])) //this is set if only source is not available.
			echo "Detecte Source Languge : ".$obj['data']['translations'][0]['detectedSourceLanguage']."n";		
	}
}
else
	echo "UNKNOW ERROR";

function translate($api_key,$text,$target,$source=false)
{
	$url = 'https://www.googleapis.com/language/translate/v2?key=' . $api_key . '&q=' . rawurlencode($text);
	$url .= '&target='.$target;
	if($source)
	 $url .= '&source='.$source;

	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$response = curl_exec($ch);                 
	curl_close($ch);

	$obj =json_decode($response,true); //true converts stdClass to associative array.
	return $obj;
}	

?>

PHP Example Using file_get_contents()

<?php
$api_key = 'PUT_YOUR_SERVER_KEY_HERE';
$text = 'How are you';
$source="en";
$target="fr";

$url = 'https://www.googleapis.com/language/translate/v2?key=' . $api_key . '&q=' . rawurlencode($text);
$url .= '&target='.$target;
$url .= '&source='.$source;

$response = file_get_contents($url);
$obj =json_decode($response,true); //true converts stdClass to associative array.
if($obj != null)
{
	if(isset($obj['error']))
	{
		echo "Error is : ".$obj['error']['message'];
	}
	else
	{
		echo "Translsated Text: ".$obj['data']['translations'][0]['translatedText']."n";
	}
}
else
	echo "UNKNOW ERROR";

?>

4) Google Translate API Java Example.

To use Translate API in Java, you need to get Google API “Server Key”.   GSON Library is used to parse JSON text.

You can use the below Java code to translate text.

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
/**
 *
 * @author Ravishanker Kusuma
 */
public class GoogleTranslate {

    private String key;

    public GoogleTranslate(String apiKey) {
        key = apiKey;
    }

    String translte(String text, String from, String to) {
        StringBuilder result = new StringBuilder();
        try {
            String encodedText = URLEncoder.encode(text, "UTF-8");
            String urlStr = "https://www.googleapis.com/language/translate/v2?key=" + key + "&q=" + encodedText + "&target=" + to + "&source=" + from;

            URL url = new URL(urlStr);

            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            InputStream stream;
            if (conn.getResponseCode() == 200) //success
            {
                stream = conn.getInputStream();
            } else
                stream = conn.getErrorStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            JsonParser parser = new JsonParser();

            JsonElement element = parser.parse(result.toString());

            if (element.isJsonObject()) {
                JsonObject obj = element.getAsJsonObject();
                if (obj.get("error") == null) {
                    String translatedText = obj.get("data").getAsJsonObject().
                    get("translations").getAsJsonArray().
                    get(0).getAsJsonObject().
                    get("translatedText").getAsString();
                    return translatedText;

                }
            }

            if (conn.getResponseCode() != 200) {
                System.err.println(result);
            }

        } catch (IOException | JsonSyntaxException ex) {
            System.err.println(ex.getMessage());
        }

        return null;
    }
    public static void main(String[] args) {

        GoogleTranslate translator = new GoogleTranslate("PUT_YOUR_KEY_HERE");
        String text = translator.translte("How are you. I am fine", "en", "fr");
        System.out.println(text);
    }
}

 

5) Google Translate API JavaScript Example.

To use Translate API in JavaScript, you need to get Google API “Browser Key”. We can pass callback parameter in the URL Request, So callback function is invoked when the request is successful.
Sample GET Request:

https://www.googleapis.com/language/translate/v2?key={YOUR_API_KEY}&source=en&target=de&callback=showIt&q=How%20are%20you

Response is:

showIt({
 "data": {
  "translations": [
   {
    "translatedText": "Wie geht es Ihnen"
   }
  ]
 }
}
);

Below is the JavaScript example:
Google Translate API in Javascript

We are dynamically adding a script to head, So when the request is successful showIt() function called.

<html>
  <body>
  <head>
  </head>
    <b>English Text:</b><div id="text">How are you</div> <br>

    <b>Converted Text(Hindi):</b> <span id="translation"></span>
    <script>
      function showIt(response) {
      	if(response.data)
	        document.getElementById("translation").innerHTML += "<br>" + response.data.translations[0].translatedText;
	        else
	        alert("Error:"+response.error.message)
      }
    </script>
    <script>
      var text = escape(document.getElementById("text").innerHTML);
      var key="PUT_YOUR_BROWSER_KEY_HERE";
      var source="en";
      var dest="hi";

      var url = 'https://www.googleapis.com/language/translate/v2?';
      	 url += 'key='+key+'&source='+source+'&target='+dest+'&callback=showIt&q='+text;
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = url;
      document.getElementsByTagName('head')[0].appendChild(script);
    </script>
  </body>
</html>

 

If you want to translate text with AJAX call, you can use the below example.

<html>
  <body>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  
  </head>
   <b>Text:</b> <input type="text" id="text" value="How are you"/> <br>
   	<b>Target Langugage:</b> 
   	<select id="target">
   	<option value="de">Germany</option>
   	<option value="hi">Hindi</option>
   	<option value="fr">French</option>
   	</select>
	<br>
	<input type="button" value="Translate"  onclick="translate()" /> <br> <br>
	<b>Translated Text:</b><div id="translated"></div>   
    <script>
    function translate()
    {
		$.get("https://www.googleapis.com/language/translate/v2",
			{
			key:"PUT_YOUR_BROWSER_KEY",
			source:"en",
			target:$("#target").val(),
			q:$("#text").val()
			},
			function(response)
			{
				$("#translated").html(response.data.translations[0].translatedText);

			},"json") .fail(function(jqXHR, textStatus, errorThrown) 
			{
				alert( "error :"+errorThrown );
			});
    }
    </script>
  </body>
</html>

Reference: Google Documentation