logo

NJP

Google Translate API with ServiceNow

Import · Mar 26, 2020 · article

In this article, i will show you how you can leverage the Google Translate API within ServiceNow.

First, you need to register on Google cloud and enable Google Translation API. This will give you API key, which i suggest you store it in ServiceNow as a system property.

In this article, i will show you how you can translate the text from a specific field of Incident record into the logged in user selected language on click of a button.

For this, we need the following

  • UI Action on the Incident record
  • Script Include to communicate with the Google API and return the translated Text

UI Action - Translate

image

In the script field, add this code.

function TranslateText() {
    console.log("value of description is "+g_form.getValue("description"));
    var ga = new GlideAjax('Translate');
    ga.addParam('sysparm_name','translateText');
    ga.addParam('sysparm_text',g_form.getValue("description"));
    ga.getXMLAnswer(callback);
    function callback(response)
    {
        var answer = response;
        g_form.setValue("description",answer);
    }
}

Script Include

var Translate = Class.create();
Translate.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    translateText : function(){
        var text = this.getParameter("sysparm_text");
        //get the user language.
        var user_language =gs.getUser().getLanguage();
        var request = new sn_ws.RESTMessageV2();
        request.setHttpMethod('post');
        //set the Google Translate API.

request.setEndpoint('https://translation.googleapis.com/language/translate/v2');
        //get the API key
        var api_key = gs.getProperty("google.translate.key");
        request.setQueryParameter("key",api_key);
        request.setQueryParameter("q",text); //Text to translate
        request.setQueryParameter("target",user_language); //language in which to translate
        var response = request.execute();
        var httpResponseStatus = response.getStatusCode();
        gs.log("Response status code is "+httpResponseStatus);
        if(httpResponseStatus==200) {
            responseObj = response.getBody();
            var res = JSON.parse(responseObj);
            var translated_text =res.data.translations[0].translatedText;
            JSUtil.logObject(res.data);
            return translated_text;
        } else {
            //error
            gs.log(response.getErrorCode()+"---"+response.getErrorMessage());
        }   
    },
    type: 'Translate'
});

Let me know if you have any questions in the comments.

Mark the article as helpful and bookmark if you found it useful.

View original source

https://www.servicenow.com/community/developer-articles/google-translate-api-with-servicenow/ta-p/2322313