Build Your Own Language Translation API with ExpressJS and OpenAI

Joshua Agbomeikhe
6 min readFeb 13, 2023

--

Full project on GitHub

Building a language translation API can be a valuable tool for many applications, from e-commerce websites to mobile apps. With the rise of artificial intelligence and machine learning, it’s easier than ever to develop this type of API and leverage the power of advanced models to translate text from one language to another. In this article, we’ll be building a simple language translation API using the Express framework and OpenAI’s language model.

Prerequisites:

  1. Basic knowledge of JavaScript and Node.js
  2. A free OpenAI API key, which you can obtain by signing up on the OpenAI website
  3. Node.js and npm installed on your computer

Step 1: Setting up the Environment

The first step is to set up the development Environment. To do this, create a new directory and initialize npm by running the following commands in the terminal:

mkdir translate-api
cd translate-api
npm init

You can create the directory in your preferred location and name it anything.

Just remember to initialise npm in the new directory by running “npm init”.

Step 2: Installing dependencies

In this step, we’ll install the dependencies: dotenv, body-parser, openai and express. The dotenv library allows us to store our OpenAI API key in a .env file, so it’s not committed to the source code, and the body-parser library allows us to parse incoming request bodies in a middleware before handling them in our routes.

Install the dependencies by running the following command:

npm install dotenv body-parser express openai

Step 3: Write some code! -Index.js-

Now, create an index.js file and add the following code to get started:

const express = require("express");
const dotenv = require("dotenv");
const bp = require("body-parser");
const { Configuration, OpenAIApi } = require("openai");

// Load environment variables from the .env file
dotenv.config();

// Create an Express app and configure middlewares
const app = express();
app.use(bp.json());
app.use(bp.urlencoded({ extended: true }));

This code sets up a basic Express app and configures some middlewares.

The first line imports the Express framework, which is a popular web application framework for Node.js.

The second line imports the dotenv package, which is used to load environment variables from a .env file.

The third line imports the body-parser middleware, which is used to parse incoming request bodies.

The fourth line imports the OpenAI API client and Configuration objects from the openai package, which will be used to interact with the OpenAI API.

The dotenv.config() method call is used to load the environment variables from the .env file.

The app.use method calls are used to configure the Express app to use the body-parser middleware, which will parse the JSON and URL-encoded request bodies.

Step 4: Configure the OpenAI API client with the API key

Still in the index.js, add this code to configure the OpenAI API client with the API key. <.<

// Configure the OpenAI API client with the API key
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

A Configuration object is created and initialized with the API key, which is obtained from the environment variable process.env.OPENAI_API_KEY.

Then, a OpenAIApi object is created and initialized with the configuration object. This object will be used to interact with the OpenAI API.

Now that the OpenAI API client is configured, it can be used to make API requests to the OpenAI API to generate text, perform machine translation, or any other task that the OpenAI API supports.

Step 5: Define the target languages

// Array of allowed target languages
const allowedLanguages = ["French", "German", "Spanish", "Italian", "Pidgin"];

This code defines an array allowedLanguages that contains a list of target languages that are allowed for translation. These are the languages that the translation service supports, and any requests for translation to a language that is not in this list will be rejected.

The list of allowed languages can be customized as needed by adding or removing items from the array.

Step 6: Define an endpoint to handle and validate translation requests

app.post("/translate", (req, res) => {
// Extract the text to translate and the target language from the request body
const text = req.body.text;
const language = req.body.language;

// Check if the text to be translated is not empty
if (!text) {
return res.status(400).send({ error: "Text to be translated cannot be empty" });
}

// Check if the target language is one of the allowed languages
if (!allowedLanguages.includes(language)) {
return res.status(400).send({ error: `Translation to ${language} is not supported` });
}

// Use OpenAI API to translate the text
openai
.createCompletion({
model: "text-davinci-003",
prompt: `Translate '${text}' from English to ${language}`,
temperature: 0,
max_tokens: 200,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
})
.then((response) => {
// Extract the translated text from the API response
const translatedText = response.data.choices[0].text;

// Send the translated text back to the client
res.send({ translatedText });
});
});

// Start the Express app and listen on port 3000
app.listen(3000, () => {
console.log("Translation API listening on port 3000");
});

This code defines an endpoint for handling translation requests.

The endpoint is created using the app.post method and is defined at the path /translate. This means that a client can make a POST request to the URL http://<server-host>:<port>/translate to send a translation request to the server.

The function passed to the app.post method handles the incoming translation request. It extracts the text to be translated and the target language from the request body, which should be in JSON format.

The function first checks if the text to be translated is not empty. If the text is empty, it returns a response with a 400 Bad Request status code and an error message indicating that the text cannot be empty.

The function then checks if the target language is one of the allowed languages, which are stored in the allowedLanguages array. If the target language is not supported, the function returns a response with a 400 Bad Request status code and an error message indicating that the translation to that language is not supported.

If both the text and target language are valid, the function uses the OpenAI API to translate the text. It creates a completion request using the openai.createCompletion method, passing in the model ID, prompt, and other parameters that control the translation.

The openai.createCompletion method returns a Promise that resolves to the API response. The response contains the translated text, which is extracted from the response and returned to the client in a JSON format.

This endpoint can be used to translate text from English to one of the supported target languages, using the OpenAI API.

Completed Index.js

Your completed index.js script should now look like this and be ready to be deployed and tested.

const express = require("express");
const dotenv = require("dotenv");
const bp = require("body-parser");
const { Configuration, OpenAIApi } = require("openai");

// Load environment variables from the .env file
dotenv.config();

// Create an Express app and configure middlewares
const app = express();
app.use(bp.json());
app.use(bp.urlencoded({ extended: true }));

// Configure the OpenAI API client with the API key
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

// Array of allowed target languages
const allowedLanguages = ["French", "German", "Spanish", "Italian", "Pidgin"];

// Define an endpoint to handle translation requests
app.post("/translate", (req, res) => {
// Extract the text to translate and the target language from the request body
const text = req.body.text;
const language = req.body.language;

// Check if the text to be translated is not empty
if (!text) {
return res.status(400).send({ error: "Text to be translated cannot be empty" });
}

// Check if the target language is one of the allowed languages
if (!allowedLanguages.includes(language)) {
return res.status(400).send({ error: `Translation to ${language} is not supported` });
}

// Use OpenAI API to translate the text
openai
.createCompletion({
model: "text-davinci-003",
prompt: `Translate '${text}' from English to ${language}`,
temperature: 0,
max_tokens: 200,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
})
.then((response) => {
// Extract the translated text from the API response
const translatedText = response.data.choices[0].text;

// Send the translated text back to the client
res.send({ translatedText });
});
});

// Start the Express app and listen on port 3000
app.listen(3000, () => {
console.log("Translation API listening on port 3000");
});

Starting the server

To start the translation API server, simply run the following code in your terminal in the directory:

node index.js

Testing

Once the app is running, you can test it by sending a POST request to http://localhost:3000/translate with a JSON payload that includes the text you want to translate and the target language. For example, you can use a tool like curl to send a request like this:

curl -X POST -H "Content-Type: application/json" -d '{"text": "Hello, World!", "language": "German"}' http://localhost:3000/translate

You should receive a response from the server that includes the translated text. for example

{
"translatedText": "\n\nHallo Welt!"
}

In conclusion, with this code, you’ll be able to translate even your deepest, darkest thoughts into other languages. Just don’t be surprised if your musings on the meaning of life get translated into Italian and come back as a recipe for pizza. Happy translating!

--

--