Building a Simple Translation REST API using Google Cloud Translation API, FastAPI, and Python

1. Python Code

Create a file named: google_cloud_tr.py

from fastapi import FastAPI
from google.cloud import translate_v3 as translate
app = FastAPI()
PROJECT_ID = "<your-project-id>"
LOCATION = "global"
@app.get("/translate")
def translate_text(text: str, target: str):
client = translate.TranslationServiceClient()
parent = f"projects/{PROJECT_ID}/locations/{LOCATION}"
response = client.translate_text(
request={
"parent": parent,
"contents": [text],
"mime_type": "text/plain",
"target_language_code": target,
}
)
return {
"translatedText": response.translations[0].translated_text
}

2. Provide the Google Cloud JSON Key as an Environment Variable

  • Search for and enable: Cloud Translation API
  • Double check: APIs & Services > Enabled APIs
  • Then: IAM & Admin > Service Accounts

Steps:

  • Create a Service Account
  • Add one of these roles:
    • Cloud Translation API User
    • Cloud Translation Admin
    • or a higher role
  • Create and download the JSON key (e.g.: service-account.json)
  • Save it inside your project directory (D:\path\to\directory\google-cloud-translation\)

Provide the JSON key path as an environment variable:

$env:GOOGLE_APPLICATION_CREDENTIALS="D:\path\to\directory\google-cloud-translation\service-account.json"

3. Run the API

Create and activate a virtual environment:

python -m venv venv
.\venv\Scripts\Activate.ps1

Install prerequisites:

pip install google-cloud-translate fastapi uvicorn

Run the API:

uvicorn google_cloud_tr:app --reload

4. Test the Result

Request:

GET http://127.0.0.1:8000/translate?text=The Strait of Hormuz has emerged as the central battleground of the Iran conflict.&target=es

Example response:

{
"translatedText": "El Estrecho de Ormuz ha surgido como el principal campo de batalla del conflicto con Irรกn."
}

Note:

Google Cloud Translation mainly handles language translation.
For advanced regional localization (such as Puerto Rico Spanish, slang, or tone-specific translation), an LLM-based approach like OpenAI may provide more natural results. Please refer this.

#fastapi, #python

Building a Simple Translation REST API with OpenAI, FastAPI, and Python

1. Python code

Create a file named: openai_tr.py

from fastapi import FastAPI
from pydantic import BaseModel
from openai import OpenAI
import os
import logging
# Logging Configuration
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s : %(message)s"
)
logger = logging.getLogger(__name__)
# OpenAI Client
client = OpenAI(
api_key=os.getenv("OPENAI_API_KEY")
)
# FastAPI App
app = FastAPI()
# Request Model
class TranslationRequest(BaseModel):
text: str
targetLanguage: str
# Locale Mapping
LOCALE_MAP = {
"es-PR": "Puerto Rico Spanish",
"es-MX": "Mexican Spanish",
"es-ES": "Spain Spanish",
"es-US": "United States Spanish",
"fr-CA": "Canadian French",
"pt-BR": "Brazilian Portuguese"
}
# Translation API
@app.post("/api/translations")
def translate(request: TranslationRequest):
locale_name = LOCALE_MAP.get(
request.targetLanguage,
request.targetLanguage
)
prompt = f"""
Translate the following text into natural {locale_name}.
Rules:
- Preserve tone and meaning
- Keep placeholders unchanged
- Keep HTML tags unchanged
- Avoid robotic translation
- Return only the translated text
Text:
{request.text}
"""
# Logging
logger.info("======================================")
logger.info("Translation Request Received")
logger.info("Target Language: %s", request.targetLanguage)
logger.info("Locale Name: %s", locale_name)
logger.info("Original Text: %s", request.text)
logger.info("Prompt:\n%s", prompt)
try:
response = client.chat.completions.create(
model="gpt-5",
messages=[
{
"role": "system",
"content": "You are a professional localization translator."
},
{
"role": "user",
"content": prompt
}
]
)
translated_text = response.choices[0].message.content
logger.info("Translated Text: %s", translated_text)
logger.info("======================================")
return {
"translatedText": translated_text,
"targetLanguage": request.targetLanguage
}
except Exception as e:
logger.exception("Translation Error Occurred")
return {
"error": str(e)
}

2. Provide the OpenAI API key as an environment variable

Go to the OpenAI API keys page and create a new secret key. OpenAIโ€™s quickstart also uses the OPENAI_API_KEY environment variable pattern for SDK authentication.[see]

$env:OPENAI_API_KEY="<your api key>"

3. Run the API

Create and activate a virtual environment:

python -m venv venv
.\venv\Scripts\Activate.ps1

Install prerequisites:

pip install openai fastapi uvicorn

Run the API:

uvicorn openai_tr:app --reload

4. Test the result

POST request:

POST http://127.0.0.1:8000/api/translations

Body:

{
"text": "The Strait of Hormuz has emerged as the central battleground of the Iran conflict. The passage of a handful of oil and gas tankers in recent days, apparently with Tehranโ€™s consent, hints at tacit acceptance โ€‹of its control. This foreshadows a more dangerous phase in what is fast turning into a Hormuz war.",
"targetLanguage": "es-PR"
}

#fastapi, #openai, #python, #transator