Google Translate

The Translation API uses Google's neural machine translation technology to instantly translate texts into 100+ languages, allowing you to reach global markets and engage with audiences from around the world seamlessly.

Use the Google Cloud Translation API with Webhooks from Agility to translate content that has been saved in Agility CMS into other language(s).

Setting up a Google Project

To start using Google Cloud Translation, create a new project in your Google Cloud Platform Console.

Creating Google Project on agilitycms.com

Give your project a name, then click create.

Give your project a name 

Step 1: Enable the API

Once you've created a project, search for the Google Cloud Translation API and enable it within your project.

Enable Google Translate API

Note

You'll need to enter billing details upon enabling the app, but Google offers a $300 credit as a free trial.

Step 2: Create a Service Account

The next step is to set up authentication with a service account so you can access the API from your website or application. In the Cloud Console, create a service account.

Creating a service account for Google Translate 

Enter a name for your Service account, then create and continue.

Service account details in Google Translate 

Grant your Service Account the Owner role, then click done.

Grant Google Translate service account roles

Step 3: Create a Service Account Key

In the Cloud Console, click on the email address for the service account you created.

Create a Google Translate service account key 

Click on Keys, then Create a new key.

  Click on Keys, then Create a new key.  

Click Create, and a JSON key file will be downloaded to your computer.

Save the JSON key that gets downloaded to your computer, as we'll need to use this in our project later in the tutorial.

Create private key for Agility CMS Service Account 

Make the content on your Agility CMS powered website or application multilingual with fast, dynamic and real-time translation from Google's Translation API.

Setting up an Agility CMS Website

Sign up for a Free Agility CMS Account. Once you have an account, you'll be able to select a starter and create an Instance.

Getting Started with Agility CMS

Create Content in Agility CMS

For this example, we're going to work with a list of News Articles. When we save a News Article in English, we'll set up a Webhook to fire off and translate the content into French.

Step 1: Create a News Content Model

To create a new Content Model called News, head to Models > Content Models, then click Add.

Create a news content model 

We're going to keep the Content Model fairly simple, with the following Fields:

Title => Text Field

Slug => Friendly URL (Custom Field)

Content => HTML Field

Step 2: Initialize a News Listing Content List

Create a new Content List with the News Content Model you created.

Initialize news listing content list 

Name the Content List News Listing, then click Create Content.

Add new content in Agility CMS for Google Translate 

Step 3: Create a News Article

Head to Content > News Listing and add a new item to your list.

News listings in Agility CMS

Add a Title, Slug, and some Content then Save the item.

Add title and slug in Agility CMS 

Step 4: Add a New Locale

Let's create a new Locale so we can store our translated content. To create a new Locale, head to Settings > Locales, then add your new Locale. For this example, we'll be using French (fr).

Adding a new locale in Agility CMS

You can now see a News Listing Content List for your new Locale. There's no content in it yet, but we'll change that with the Google Cloud Translate API.

Change to Google translate in Agility CMS 

Set up Backend Service

It's time to set up our backend service that will accept a message from Agility CMS about updated content. the backed will connect to Google Translate and the Agility Content Fetch API to send the details of what needs to be translated and to receive a translated response.

Using a Webhook from Agility, we'll notify the backend service of what content to translate. Once the content is translated, we can use the Agility Content Management API to save the translated content in Agility.

Step 1: Create Backend Service

For this example, we're creating a simple backend with an API Route (Serverless Function):

/api/translate/translateNews.js

export default async function handler(req, res) {

  // store webhook data into variables
  const referenceName = req.body.referenceName;
  const state = req.body.state;
  const languageCode = req.body.languageCode;
  const contentID = req.body.contentID;

  if (!referenceName || !referenceName.endsWith("newslisting")) {

    //kickout
    res.status(200).end();

    return;
  }

  if (contentID && state === "Saved" && languageCode === "en-us") {

    // get post in English

    // use Google Translate API to Translate

    // use Agility Content Management API to save translated content in Agility
  
  }

  res.status(200).json();
}

Step 2: Set up Agility CMS Webhook

Next, lets set up a Webhook that will notify our backend of what content to translate. To create a new Webhook in Agility, head to Settings > Webhooks, then click Add.

Setting up an Agility CMS webhook 

Give your Webhook a Name, add the URL for your backend service, and make sure the Webhook is enabled for Save Events. You can test your Webhook by sending a sample payload.

Give your webhook a name 

Step 3: Get Details of News Item to Translate

With the help of the Agility Content Fetch SDK, let's get the details of a News Item saved in the English Locale.

/utils/getNewsArticle.js

import agility from "@agility/content-fetch";

const getNewsArticle = async ({ contentID, languageCode }) => {

  // set up API
  const api = await agility.getApi({
    guid: "YOUR_INSTANCE_GUID",
    apiKey: "YOUR_INSTANCE_API_KEY"
  });

  // get news article
  const article = await api.getContentItem({
    contentID,
    languageCode,
  });

  const fieldsToTranslate = {
    title: article.fields.title,
    slug: article.fields.slug,
    content: article.fields.content,
  };

  return fieldsToTranslate;

};

export default getNewsArticle;

Step 4: Use Google Cloud Translation API

Now it's time to use the Google Cloud Translation API to translate our Content.

/utils/translateContent

const translateContent = async ({ title, slug, content, referenceName }) => {

  // language to translate to
  const translateTo = "fr";

  // set up Google Cloud Translation
  const { Translate } = require("@google-cloud/translate").v2;

  const translate = new Translate({
    projectId: "YOUR_PROJECT_ID",
    keyFilename: path.resolve("./KEY_FILE_NAME.json"),
  });

  const [translatedTitle] = await translate.translate(title, translateTo);

  const [translatedSlug] = await translate.translate(slug, translateTo);

  const [translatedContent] = await translate.translate(content, translateTo);

  return {
    title: translatedTitle,
    slug: translatedSlug.toLowerCase().replace(/[^A-Z0-9]/gi, "-"),
    content: translatedContent,
  };
};

export default translateContent;

Remember that JSON file you saved from earlier? Add it to the root of your project, and reference it as the keyFileName along with the projectId when configuring the Translation API.

Step 5: Save Translated Content in Agility

To save the translated content in Agility, we can use the Content Management API.

import agilityMgmt from "@agility/content-management";

const saveTranslatedContent = async ({
  title,
  slug,
  content,
  referenceName,
}) => {
  // set up Agility Content Management API
  const mgmtApi = agilityMgmt.getApi({
    location: "USA",
    websiteName: "YOUR_INSTANCE_WEBSITE_NAME",
    securityKey: "YOUR_INSTANCE_SECURITY_KEY",
  });

  console.log("slug", slug);

  // set up content item to save
  let contentItem = {
    contentID: -1,
    fields: {
      Title: title,
      Slug: slug,
      Content: content,
    },
  };

  // save item in Agility in French Locale
  mgmtApi
    .saveContentItem({
      contentItem,
      languageCode: "fr",
      referenceName,
    })
    .then(function (contentID) {
      console.log(`Created ContentID ${contentID} in French Locale`);
    })
    .catch(function (error) {
      console.log(error);
    });
};

export default saveTranslatedContent;

Here's what the final code looks like for our solution:

import getNewsArticle from "../../../utils/getNewsArticle";
import translateContent from "../../../utils/translateContent";
import saveTranslatedContent from "../../../utils/saveTranslatedContent";

export default async function handler(req, res) {

  // store webhook data
  const referenceName = req.body.referenceName;
  const state = req.body.state;
  const languageCode = req.body.languageCode;
  const contentID = req.body.contentID;

  if (!referenceName || !referenceName.endsWith("newslisting")) {
    //kickout
    res.status(200).end();
    return;
  }

  if (contentID && state === "Saved" && languageCode === "en-us") {
    
    // use content fetch api to fetch data for the item
    const fieldsToTranslate = await getNews({ contentID, languageCode });

    // translate content
    const translatedContent = await translateContent({
      title: fieldsToTranslate.title,
      slug: fieldsToTranslate.slug,
      content: fieldsToTranslate.content,
    });

    // use Content Management API to save translated content in Agility
    await saveTranslatedContent({
      title: translatedContent.title,
      slug: translatedContent.slug,
      content: translatedContent.content,
      referenceName,
    });
  }

  res.status(200).json();
}

Now when you create and save new News item, your Webhook will trigger and your backend will translate the content, and save it back into Agility.

Webhook triggering a backend translate in Agility CMS