SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software
Development resources, articles, tutorials, code samples, tools and downloads for AWS Amazon Web Services, Redshift, AWS Lambda Functions, S3 Buckets, VPC, EC2, IAM

Amazon Tranlate Service with AWS API Gateway and Python Lambda Function


AWS tutorial shows how developers can create an Amazon Lambda function which calls Amazon Translate service for text translation and expose Lambda using API Gateway. To access this API Endpoint developers require API key which should be sent via HTTP request in Header section.

This Amazon tutorial shares steps with sample Python code for Lambda function consuming Amazon Translate service, test configuration to test the translation functionality within Lambda, creating Amazon API Gateway as endpoint for external developers who will consume this service. One last step demonstrates how the API endpoint can be called within a REST project from SoapUI tool.

Create Lambda Function

Launch AWS Console.
Switch to targeted region. I'll use Paris for this tutorial.
Open AWS Lambda service.
Create a function and author from scratch.

Name of the Lambda function is "translate"
For Runtime select "Python 3.7"
Role is important. I'll choose an existing role with enough authorization. (AC3LambdaCallingTranslate)
Press "Create function"

create Amazon Lambda function using Python

When the Python codes of AWS Lambda function "translate" is displayed in "Function code" inline code editor, replace all content with following

Please note the idents are important otherwise Python will produce error

import json
import logging
import boto3
import os

def lambda_handler(event, context):

  translate = boto3.client(service_name='translate', region_name='eu-west-1', use_ssl=True)

  try:
    review_id = event["queryStringParameters"]['review_id']
  except:
    review_id = "1"

  try:
    source_language = event["queryStringParameters"]['source_language']
  except:
    source_language = "auto"

  try:
    target_language = event["queryStringParameters"]['target_language']
  except:
    target_language = "it"

  try:
    review = event["queryStringParameters"]['review']
  except:
    review = "My name is Eralper"

  result = translate.translate_text(Text=review, SourceLanguageCode=source_language, TargetLanguageCode=target_language)

  return {
    'statusCode': 200,
    'body': json.dumps(result.get('TranslatedText'))
  }
Python Code for AWS Lambda Function for Translate

It is better to add tags to manage this Lambda function among all other AWS resources.

I use following tags:
region: Paris
use: Translation
type: Lambda
description: Consumes Amazon Translate service using input parameters

All other Lambda settings related with Lambda function itself is left as default.

Save your Lambda function


Test Lambda Function

To test Lambda function "translate" before continue deeper configuration options, click "Test" button at the top menu. This will execute the Lambda function using test data.

test AWS Lambda function code

First of all, Lambda developer will be requested to create and configure a test event.
Make sure "Create new test event" is selected.
Among the long list of "Event templates", choose "Amazon API Gateway AWS Proxy"
Name the event as "test".

Within the JSON representation of the event data, find the section for "queryStringParameters"
Remove "foo" line and make sure the event data is similar to following

...
"queryStringParameters": {
  "review": "Hello, welcome to kodyaz.com",
  "target_language": "it",
  "source_language": "auto",
  "review_id": "1"
},
...
Query String Parameters for Test

Since we are going to use GET method with URL parameters, above queryStringParameters section will not help us to provide sample data for our Lambda function.

You will realize these are mapping to event array values in our Python code shared with you in this tutorial before.

test data configuration for Amazon Lambda function execution

Press Create to complete test event creation.

Now press "Test" button once more to execute our Lambda function test.
At the top right below the Test button, you will hopefully see "Execution result: succeeded" message marked with green area. If an error has occured you will see error message and error details on top of a red layout.

successfull execution of AWS Lambda function


Add API Gateway as Trigger to Translate Lambda Function

On Lambda function Designer screen, developers will see the "Add triggers" on the left column. Click on API Gateway to create an API Gateway automatically that will trigger our Lambda function created early in this AWS tutorial.

trigger Amazon Lambda function from API Gateway

You can realize that "Configuration required" mark on the API Gateway tile.
When the programmer clicks on the tile he or she will be directed to area where API Gateway configuration can be managed. Or you can scroll-down and fill "Configure triggers" section

Choose: Create a new API
For security, among all options choose "Open with API key"

Gateway API with Open Key

If you click on "Additional settings" you can define "Deployment stage" like dev, test, prod, etc as a common practise. I will choose "prod" for the deployment stage. This means the API Gateway that will be created will be deployed to this stage automatically.

Click the Add button at the end of this configuration section. Since there are binary media addition button be careful you click on the correct Add button.

Until this point the API Gateway is not yet created.
At the top of the screen, click on Save button. This save action will create the API Gateway that will trigger the Lambda function.

After Save, API Gateway section will be populated with following data also seen as a screenshot image.
Please note that this API Key must be kept as a secret among who will use this API. If you want this API be public, you should choose "Open" option instead of "Open with Key" for security configuration option.

API Gateway
translate-API
arn:aws:execute-api:eu-west-3:411387743251:3hy5u07aqc/*/*/translate
Details
API: api-gateway/4ty5r29aog/*/*/translate
API endpoint: https://3hy5u07aqc.execute-api.eu-west-3.amazonaws.com/prod/translate
API key: dRnjc9N27Gbgj7fDpiY5I6fKt6tK407G9E2hof3m
API name: translate-API
Authorization: NONE
Enable metrics and error logging: No
Method: ANY
Resource path: /translate
Security: NONE_KEY
Stage: prod

Please note that this API endpoint and API key is important.
Especially for API Key, you will see this key only once on this screen so keep it in a safe place since you will use it later.

configuration of Gateway API to trigger Amazon Lambda function


AWS API Gateway

Now when you are on AWS Lambda screen, on API Gateway section, click on the "translate-API" (name of the API) weblink which will redirect you to API Gateway configured for this Lambda function.

Amazon Lambda developer will see that Resources tab of the API is displayed. You can switch to Stages tab from left menu. On this "prod" stage section (remember we have defined the stage name during API configuration section of the Lambda function trigger creation), you will see "invoke URL". This is the end point we will use for our sample AWS tutorial translate API


Consume Translate API using SoapUI

If you have SoapUI installed on your machine, launch it.
Create a new REST project and use the API endpoint you have created as Lambda function trigger.

create REST project in SOAPUI

You will see in Resource section we have stage and action.
You had to type query string parameter values manually on Request tab or using the Parameters input area.

It is important, you need to provide the API Key in Headers section using the key name "X-API-Key" and value pair. Remember we had this API key value when we have created the Gateway API as trigger for our AWS translate Lambda function.

When the REST request is executed the JSON response returns us the translated text we have sent with our request

create API request to test Amazon Translate service via HTTP Request



AWS


Copyright © 2004 - 2024 Eralper YILMAZ. All rights reserved.