Martin Normark's blog

Posted on by Martin Normark


A long time ago, I wrote a blog post about how to translate text in C# using Google Translate. Since then, an official AJAX API has been released, which is a much better solution. Reading the comments of the blog post indicates that the code was broken quite quickly!

Google’s AJAX Language API, also includes functionality to detect language from a given string. All you can do on translate.google.com you can do via the API. Reading the class reference for the Translation API, for Flash and other Non-Javascript environments gives us the information we need to perform translations from C#. Most important is the URL and the parameters required and accepted.

Another very important thing we can read in the documentation is this:

Applications MUST always include a valid and accurate http referer header in their requests

We must remember to add a valid referrer when making the actual call!

The response object

Google’s AJAX Language APIs uses JSON, and returns a JSON object containing 3 properties:

  • responseData
  • responseDetails
  • responseStatus

This means we need to have some C# objects that we can use to deserialize the JSON returned from Google. I’m using a generic class called GoogleAjaxResponse<T>, with T being the specific class I want the JSON to be deserialized to.

using System.Runtime.Serialization;

namespace Milkshake.Integration.Google
{
	/// Defines a response from one of Google's AJAX APIs.
	/// The type of object, being returned.
	[DataContract]
	public class GoogleAjaxResponse<T>
	{
		///
		/// Gets or sets the response data.
		///
		///
		/// The responseData from Google AJAX API Call
		///
		/// The response data.
		[DataMember(Name = "responseData", Order = 0)]
		public T ResponseData { get; set; }
	}
}

To deserialize the Translation specific JSON, I use the TranslationResponse class:

using System.Net;
using System.Runtime.Serialization;

namespace Milkshake.Integration.Google.Translate
{
	/// Defines a response from the Google AJAX Translate API.
	[DataContract]
	public class TranslationResponse
	{
		/// Initializes a new instance of the  class.
		public TranslationResponse()
		{
			this.ResponseStatus = HttpStatusCode.OK;
		}

		/// Gets or sets the translated text.
		/// The translated text.
		[DataMember(Name = "translatedText", Order = 0)]
		public string TranslatedText { get; set; }

		/// Gets or sets the response details.
		/// The response details.
		[DataMember(Name = "responseDetails", Order = 1)]
		public object ResponseDetails { get; set; }

		/// Gets or sets the response status.
		/// The response status.
		[DataMember(Name = "responseStatus", Order = 2)]
		public HttpStatusCode ResponseStatus { get; set; }
	}
}

Calling the Google AJAX Translate API

To make the actual call, we can use the HttpWebRequest and HttpWebResponse classes.

using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;

namespace Milkshake.Integration.Google.Translate
{
	/// An API Client for the Google AJAX Translate API.
	public class TranslateApi
	{
		/// The JavaScript serializer
		private JavaScriptSerializer _Serializer = new JavaScriptSerializer();

		/// Translates the text.
		public string TranslateText(string inputText, string sourceLanguage, string destinationLanguage, string referrer, string apiKey)
		{
			string requestUrl = string.Format("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q={0}&langpair={1}|{2}&key={3}", HttpUtility.UrlEncode(inputText), sourceLanguage.ToLowerInvariant(), destinationLanguage.ToLowerInvariant(), apiKey);

			try
			{
				using (HttpClient http = new HttpClient(requestUrl))
				{
					http.AddReferrer(referrer);
					http.ExecuteRequest();

					string responseJson = http.GetResponseString();

					GoogleAjaxResponse<TranslationResponse> translation = this._Serializer.Deserialize<GoogleAjaxResponse<TranslationResponse>>(responseJson);

					if (translation != null && translation.ResponseData != null && translation.ResponseData.ResponseStatus == HttpStatusCode.OK)
					{
						return translation.ResponseData.TranslatedText;
					}
					else
					{
						return String.Empty;
					}
				}
			}
			catch
			{
				return String.Empty;
			}
		}
	}
}

The response JSON and translated text

Doing a simple test, I translate “Hello world” from English to Danish, and I can see that it works like a charm.

image

Professional translations - even via API!
translation agency

About the author

Martin Normark Martin Normark works as a freelance web developer (consultant). He blogs about web, software and programming experiments, daily code battles, specific How To posts and what else comes to mind.

Posted on by Martin Normark | Posted in C#, Internationalization | Tagged , ,

  • Pingback: Translate text in C#, using Google Translate | Martin Normark's blog

  • Daryl Blanchett

    Thanks for the sample it was extremely helpful.
    There were a couple of omissions in the posted code though. The GoogleAjaxResponse class declaration was incorrect it should look like this:

    [DataContract]
    public class GoogleAjaxResponse

    Also the sample code deserialization line should be as follows
    GoogleAjaxResponse translation = _Serializer.Deserialize<GoogleAjaxResponse>(responseJson);

    Cheers

  • Felipe

    Nice post!

    Missing code here?

    GoogleAjaxResponse
    translation = this._Serializer.Deserialize
    >(responseJson);

    Cheers

  • http://martinnormark.com Martin H. Normark

    @Daryl and @Felipe:

    Thanks for your comments.

    The missing fragments of the code, is due to WordPress stripping away the < and >. I think it’s time to use Syntax Highlighter or something similar.

  • Michael Reinecke

    nice post but my VS2010 @.Net4.0 can’t resolve DataContract & HttpClient, could you just post the sample-projekt-files?

  • http://www.milkshakecommerce.com/ecommerce-blog Martin H. Normark

    Hi Michael

    DataContract is part of the framework, you might need to add reference to the System.Runtime.Serialization.dll.

    HttpClient is my own HTTP Wrapper. It is currently not available, since I use it for commercial software. I want to move it out and into an open source project, but haven’t done so yet. I suggest you rewrite the code to use .Net’s built in HttpWebRequest: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx

  • Jeremiah Gatong

    how about the new Google Translation API  v2?

  • http://www.milkshakecommerce.com/ecommerce-blog Martin H. Normark

    I haven’t played around with it yet. It might work by changing the value of the v URL parameter, but the chances are probably small. I’d like to revisit the code once again some day.

  • Bgsjust

    Hello
    What represents the apikey parameter ? This is related with the payed translator API from google ?
    It’s the access/user key ?
    Regards

  • http://www.milkshakecommerce.com/ecommerce-blog Martin H. Normark

    Take a look at this: 
    https://developers.google.com/translate/v2/getting_started#auth and this: 
    https://developers.google.com/translate/v2/using_rest#auth

    But it does look like Google Translate has become a paid service. Don’t know if the code still works.