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:
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.
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)
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:
To start the server, simply run: python translation_service.py
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:
text
, a string to be detected.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.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