How to Build a Translate Application with Python and Flask

How to Build a Translate Application with Python and Flask

In this post, we'll learn bout to Build a Translate Application with Python and Flask (Google Translate API with Python & Flask)

In this post, we’re going to take a look at how you can use RapidAPI to get started on a project fast. With very little time invested up front, there is the potential to add a real wow factor to your latest text-based project. In particular, we’re going to look at setting up a text translation microservice that we can use to build in text translation into any app.

First, let’s take stock of what we’ll need for our text translation microservice:

  1. A Free RapidAPI Account
  2. A clean virtual environment — we’ll use Pipenv
  3. Flask (the Python web framework)

Google Translate API Overview

The Google TranslateAPI on RapidAPI is easy to navigate. There are only two endpoints exposed, and both take HTTP POST requests. This makes it an easy API to use, even for beginners.

API Endpoints:

  • Detect:
    • Request Type: POST
    • Params (1):
      • :: Param Type: String
      • :: Param Value: Text from which language will be detected.
  • Translate:
    • Request Type: POST
    • Required Params (2):
      • :: Param Type: String
      • :: Param Value: Text to be translated.
      • :: Param Type: String
      • :: Param Value: Target Language.

The inherent simplicity that comes with having only the two endpoints we need (and nothing more) is helpful for this tutorial.

Now, let’s create a root directory for our new project. From the terminal, simply run:

mkdir translation-service

Then, to enter that directory, run:

`‘cd translation-service``

Finally, create and name the one file we will need to write:

touch translation_service.py

Now, let’s get our environment set up. Install Pipenv if you don’t already have it.

Then run:

pipenv --three to create a Python3 vm, and pipenv shell to enter it.

NOTE: you are now in a Python3 virtual environment of the same name as the directory you were in when you ran the command.

Finally, let’s install Flask. Run: pip install Flask

And we’re off to the races! Let’s take a look at some code!

from flask import Flask, request
import requests

app = Flask(__name__)

DETECT_BASE_URL = 'https://google-translate1.p.rapidapi.com/language/translate/v2/detect'
TRANSLATE_BASE_URL = 'https://google-translate1.p.rapidapi.com/language/translate/v2'
HEADERS = {
   'x-rapidapi-host': "google-translate1.p.rapidapi.com",
   'x-rapidapi-key': "YOUR-VERY-OWN-RAPID-API-KEY-GOES-HERE",
   'content-type': "application/x-www-form-urlencoded"
   }

This is really where the power of this app comes in. By isolating all logic that has to do with interacting with the Google Translate API in this app, we free ourselves to interact with it in any other application (or extension of this application) we create. This process is easy because we’re already signed in, so to speak — we have our password and the rest of our particulars secure and ready to get us access at a moment’s notice.

When it isn’t being called upon, this service will just listen and wait for another server to contact it.

@app.route('/')
def health_check():
   return 'Translation Service is up.'

It’s handy to give yourself a quick heads up that things are good. We’re returning a message to what is generally referred to as the “index view” or “page”, which is denoted by the route ’/’, because it is generally the first to load.

 @app.route('/detect', methods=['POST'])
def detect():
   # parse args
   text = request.form.get('text')

   # url encode text
   long_list_of_words = text.split(' ')
   url_encoded_text = f"q={'%20'.join(long_list_of_words)}"

   payload = url_encoded_text

   # make the request
   r = requests.post(DETECT_BASE_URL, data=payload, headers=HEADERS)

   return r.json()

Above, we’ve defined our second route. This one has additional logic. First, we parse our args from the global request object that is available in the body of our functions with route decorators once we import it (as we did above). Depending on your use case, you may choose to pass your request as JSON, rather than form data. If so, simply replace form with json, as so:

` text  =  request.json.get(‘text’)`

It worth noting that we have to do a bit of text formatting here. Again, this is a nice reason to build this as a microservice. We only have to do this once, and then it’s done any time we want to use the Google Translate API.

Now, let’s create our translate route in much the same way. In this case, though, we have a second mandatory parameter. We’ll just pull it from the request like we did with the text.

@app.route('/translate', methods=['POST'])
def translate():
   # parse args
   text = request.form.get('text')
   target = request.form.get('target')

   # url encode text
   long_list_of_words = text.split(' ')
   url_encoded_text = f"q={'%20'.join(long_list_of_words)}&target={target}"

   payload = url_encoded_text

   r = requests.post(TRANSLATE_BASE_URL, data=payload, headers=HEADERS)

   return r.json()

if __name__ == '__main__':
   app.run(debug=True)

The Finished Application:

To run this locally, copy the code below, and paste it into a file called translation_service.py inside of your virtual env. Your file tree looks like this:

This is image title

To start the server, simply run: python translation_service.py

This is image title

If all has gone well, you’ll see something very much like the above. Note the virtual environment — denoted by the parens to the far left of the cursor’s line. And within that env, you have a brand new Flask app running in debug mode, which means that it will restart the server every time it detects changes to the code, which is infinitely more convenient than manually restarting every time. Take my word for it.

You will then have a server listening at http://127.0.0.1:5000 for three different routes:

  1. ‘/’ — our health check
    1. Basically, go to the address above in your browser. If you see some text, everything is working. Pro tip: we didn’t define the route method explicitly, but it defaults to a GET request, which is what the browser sends by default. Default win.
  2. ‘/detect’the, ahem, detect route
    1. This guy will be waiting for a POST request that contains the parameter text, a string to be detected.
    2. Ex: {“text”: “Words that you want the thing to do stuff with”}
  3. ‘/translate’yep
    1. This one will be waiting for a POST request that contains both text, a string to be translated AND target, also a string, and the abbreviation for the target language. For example, ‘es’ is the abbreviation for the target language Spanish.
    2. Ex: {“text”: “You guessed it. The words…”, “target”: “es”}

translation_service.py

from flask import Flask, request
import requests

app = Flask(__name__)

DETECT_BASE_URL = 'https://google-translate1.p.rapidapi.com/language/translate/v2/detect'
TRANSLATE_BASE_URL = 'https://google-translate1.p.rapidapi.com/language/translate/v2'
HEADERS = {
   'x-rapidapi-host': "google-translate1.p.rapidapi.com",
   'x-rapidapi-key': "YOUR-VERY-OWN-RAPID-API-KEY-GOES-HERE",
   'content-type': "application/x-www-form-urlencoded"
   }

@app.route('/')
def health_check():
   return 'Translation Service is up.'

@app.route('/detect', methods=['POST'])
def detect():
   # parse args
   text = request.form.get('text')

   # url encode text
   long_list_of_words = text.split(' ')
   url_encoded_text = f"q={'%20'.join(long_list_of_words)}"

   payload = url_encoded_text

   # make the request
   r = requests.post(DETECT_BASE_URL, data=payload, headers=HEADERS)

   return r.json()

@app.route('/translate', methods=['POST'])
def translate():
   # parse args
   text = request.form.get('text')
   target = request.form.get('target')

   # url encode text
   long_list_of_words = text.split(' ')
   url_encoded_text = f"q={'%20'.join(long_list_of_words)}&target={target}"
    payload = url_encoded_text

   r = requests.post(TRANSLATE_BASE_URL, data=payload, headers=HEADERS)

   return r.json()

if __name__ == '__main__':
   app.run(debug=True)

We set up our environment with Pipev, because it saves us any dependency-related frustration. It’s a real drag when your code won’t run, but it has nothing to do with the code you’ve written.

Thank you for reading!

python flask translate api

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Python REST API Tutorial - Building a Flask REST API

This Python REST API tutorial will teach you how to build a Python flask REST API. We will start by building a basic REST API then integrating that API with a Flask SQL-Alchemy Database. At the end of this video you will have a fully functioning REST API with Python and Flask.

Python Flask & Mongodb REST API (PyMongo & Flask)

En este ejemplo práctico de Python aprenderemos a crear una REST API, usando el framework web Flask y a Mongodb como base de datos NoSQL. Crearemos CRUD (CREATE, READ, UPDATE, DELETE) usando las tipicas peticiones HTTP.

Building a simple REST API with Python and Flask

In this Python tutorial, you'll learn how to create a simple REST API with Flask, Python and FlaskRESTful. We create a simple REST API with Python. We use the Flask framework and Flask_RESTful library to make it fast and easy.

Creating RESTful Web APIs using Flask and Python

Creating RESTful Web APIs using Flask and Python. A Comprehensive Guide for building Web APIs with Flask. Flask is a widely used micro web framework for creating APIs in Python. It is a simple yet powerful web framework which is designed to get started quick and easy, with the ability to scale up to complex applications.

How to Create Python RESTful API with Flask, Connexion and SQLAlchemy

Learn how to create a Python-powered RESTful API from scratch using Flask, the Connexion library and SQLAlchemy. Also covers automated validation and documentation for your API endpoints using the Swagger / OpenAPI standard.