Skip to content

Commit b584d57

Browse files
authored
Merge pull request #2694 from vaidehip86/vaidehp-feature-ApiGateway-Transcribe-python-cdk
New serverless pattern- API Gateway Translate integration in python CDK
2 parents 494afbb + bb4a080 commit b584d57

11 files changed

+391
-0
lines changed

apigw-translate-python-cdk/README.md

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# Amazon API Gateway to Amazon Translate
2+
3+
This pattern creates a REST API Gateway that can perform POST API Call to Amazon Translate's TranslateText API
4+
5+
Learn more about this pattern at Serverless Land Patterns: << Add the live URL here >>
6+
7+
Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.
8+
9+
## Requirements
10+
11+
* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
12+
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
13+
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
14+
* [Node and NPM](https://nodejs.org/en/download/) installed
15+
* [AWS Cloud Development Kit](https://docs.aws.amazon.com/cdk/v2/guide/cli.html) (AWS CDK) installed
16+
17+
## Deployment Instructions
18+
19+
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
20+
```
21+
git clone https://github.com/aws-samples/serverless-patterns
22+
```
23+
2. Change directory to the pattern directory:
24+
```
25+
cd apigw-translate-python-cdk
26+
```
27+
3. Create a virtual environment for Python:
28+
```
29+
python3 -m venv .venv
30+
```
31+
4. Activate the virtual environment:
32+
```
33+
source .venv/bin/activate
34+
```
35+
For a Windows platform, activate the virtualenv like this:
36+
```
37+
.venv\Scripts\activate.bat
38+
```
39+
5. Install the required Python dependencies:
40+
```
41+
pip install -r requirements.txt
42+
```
43+
6. Bootstrap the AWS environment, if you haven't already done so:
44+
```
45+
cdk bootstrap
46+
```
47+
7. Review the CloudFormation template AWS CDK generates for the stack:
48+
```
49+
cdk synth
50+
```
51+
8. Deploy the AWS resources:
52+
```
53+
cdk deploy
54+
```
55+
56+
9. Note the outputs from the CDK deployment process. These contain the resource names and/or ARNs which are used for testing.
57+
The deployment will create a REST API Gateway.
58+
59+
## How it works
60+
61+
This pattern deploys an Amazon API Gateway REST API with a /translate endpoint integrated with Amazon Translate’s TranslateText API. The service processes the provided text and language codes in the request body, returning the translated text or an error response if the specified language code is unsupported.
62+
63+
## Testing
64+
65+
Once the application is deployed, either use a curl or call the endpoint from Postman.
66+
67+
Example POST Request to translate text to Spanish:
68+
```
69+
curl -X POST "https://YOUR_API_ID.execute-api.YOUR_AWS_REGION.amazonaws.com/Prod/translate" -H "Content-Type: application/json" -d '{"text": "Hello, world!", "sourceLanguageCode": "en", "targetLanguageCode": "es"}'
70+
```
71+
72+
Response:
73+
```
74+
{"SourceLanguageCode":"en","TargetLanguageCode":"es","TranslatedText":"¡Hola, mundo!"}
75+
```
76+
77+
## Cleanup
78+
79+
To clean up the resources created as part of this demonstration, run the command `cdk destroy` in the directory `apigw-translate-python-cdk`. In addition, users are advised to terminate the Cloud9 EC2 instance to avoid any unexpected charges.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
{
2+
"title": "Amazon API Gateway to Amazon Translate",
3+
"description": "Create a REST API Gateway that can perform POST API Call to Amazon Translate's TranslateText API",
4+
"language": "Python",
5+
"level": "200",
6+
"framework": "CDK",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"This CDK Pattern creates a REST API Gateway. The API Gateway endpoint uses service integration to directly connect to Amazon Translate."
11+
]
12+
},
13+
"gitHub": {
14+
"template": {
15+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-translate-python-cdk",
16+
"templateURL": "serverless-patterns/apigw-translate-python-cdk",
17+
"projectFolder": "apigw-translate-python-cdk",
18+
"templateFile": "translate_api/translate_api_stack.py"
19+
}
20+
},
21+
"resources": {
22+
"bullets": [
23+
{
24+
"text": "Amazon Translate API Actions List",
25+
"link": "https://docs.aws.amazon.com/translate/latest/APIReference/API_TranslateText.html"
26+
}
27+
]
28+
},
29+
"deploy": {
30+
"text": [
31+
"cdk deploy"
32+
]
33+
},
34+
"testing": {
35+
"text": [
36+
"See the GitHub repo for detailed testing instructions."
37+
]
38+
},
39+
"cleanup": {
40+
"text": [
41+
"Delete the stack: <code>cdk destroy</code>."
42+
]
43+
},
44+
"authors": [
45+
{
46+
"name": "Vaidehi Patel",
47+
"image": "https://avatars.githubusercontent.com/u/23283229?v=4",
48+
"bio": "I'm a Solutions Architect at Amazon Web Services based in Dallas,TX. I'm a serverless enthusiast, I like to build and architect serverless applications",
49+
"linkedin": "vaidehi-patel08"
50+
}
51+
],
52+
"patternArch": {
53+
"icon1": {
54+
"x": 20,
55+
"y": 50,
56+
"service": "apigw",
57+
"label": "API Gateway REST API"
58+
},
59+
"icon2": {
60+
"x": 80,
61+
"y": 50,
62+
"service": "translate",
63+
"label": "Amazon Translate"
64+
},
65+
"line1": {
66+
"from": "icon1",
67+
"to": "icon2",
68+
"label": ""
69+
}
70+
}
71+
}

apigw-translate-python-cdk/app.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#!/usr/bin/env python3
2+
import aws_cdk as cdk
3+
from translate_api.translate_api_stack import TranslateApiStack
4+
5+
app = cdk.App()
6+
TranslateApiStack(app, "TranslateApiStack")
7+
app.synth()

apigw-translate-python-cdk/cdk.json

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
{
2+
"app": "python3 app.py",
3+
"watch": {
4+
"include": [
5+
"**"
6+
],
7+
"exclude": [
8+
"README.md",
9+
"cdk*.json",
10+
"requirements*.txt",
11+
"source.bat",
12+
"**/__init__.py",
13+
"**/__pycache__",
14+
"tests"
15+
]
16+
},
17+
"context": {
18+
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
19+
"@aws-cdk/core:checkSecretUsage": true,
20+
"@aws-cdk/core:target-partitions": [
21+
"aws",
22+
"aws-cn"
23+
],
24+
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
25+
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
26+
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
27+
"@aws-cdk/aws-iam:minimizePolicies": true,
28+
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
29+
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
30+
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
31+
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
32+
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
33+
"@aws-cdk/core:enablePartitionLiterals": true,
34+
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
35+
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
36+
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
37+
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
38+
"@aws-cdk/aws-route53-patters:useCertificate": true,
39+
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
40+
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
41+
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
42+
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
43+
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
44+
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
45+
"@aws-cdk/aws-redshift:columnId": true,
46+
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
47+
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
48+
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
49+
"@aws-cdk/aws-kms:aliasNameRef": true,
50+
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
51+
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
52+
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
53+
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
54+
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
55+
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
56+
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
57+
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
58+
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
59+
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
60+
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
61+
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
62+
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
63+
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
64+
"@aws-cdk/aws-eks:nodegroupNameAttribute": true,
65+
"@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
66+
"@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
67+
"@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false,
68+
"@aws-cdk/aws-s3:keepNotificationInImportedBucket": false,
69+
"@aws-cdk/aws-ecs:enableImdsBlockingDeprecatedFeature": false,
70+
"@aws-cdk/aws-ecs:disableEcsImdsBlocking": true,
71+
"@aws-cdk/aws-ecs:reduceEc2FargateCloudWatchPermissions": true,
72+
"@aws-cdk/aws-dynamodb:resourcePolicyPerReplica": true,
73+
"@aws-cdk/aws-ec2:ec2SumTImeoutEnabled": true,
74+
"@aws-cdk/aws-appsync:appSyncGraphQLAPIScopeLambdaPermission": true,
75+
"@aws-cdk/aws-rds:setCorrectValueForDatabaseInstanceReadReplicaInstanceResourceId": true,
76+
"@aws-cdk/core:cfnIncludeRejectComplexResourceUpdateCreatePolicyIntrinsics": true,
77+
"@aws-cdk/aws-lambda-nodejs:sdkV3ExcludeSmithyPackages": true,
78+
"@aws-cdk/aws-stepfunctions-tasks:fixRunEcsTaskPolicy": true,
79+
"@aws-cdk/aws-ec2:bastionHostUseAmazonLinux2023ByDefault": true,
80+
"@aws-cdk/aws-route53-targets:userPoolDomainNameMethodWithoutCustomResource": true,
81+
"@aws-cdk/aws-elasticloadbalancingV2:albDualstackWithoutPublicIpv4SecurityGroupRulesDefault": true,
82+
"@aws-cdk/aws-iam:oidcRejectUnauthorizedConnections": true,
83+
"@aws-cdk/core:enableAdditionalMetadataCollection": true,
84+
"@aws-cdk/aws-lambda:createNewPoliciesWithAddToRolePolicy": true
85+
}
86+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
{
2+
"title": "Amazon API Gateway to Amazon Translate",
3+
"description": "Create a REST API Gateway that can perform POST API Call to Amazon Translate's TranslateText API",
4+
"language": "Python",
5+
"level": "200",
6+
"framework": "AWS CDK",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"This CDK Pattern creates a REST API Gateway. The API Gateway endpoint uses service integration to directly connect to Amazon Translate."
11+
]
12+
},
13+
"gitHub": {
14+
"template": {
15+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-translate-python-cdk",
16+
"templateURL": "serverless-patterns/apigw-translate-python-cdk",
17+
"projectFolder": "apigw-translate-python-cdk",
18+
"templateFile": "apigw-translate-python-cdk/translate_api/translate_api_stack.py"
19+
}
20+
},
21+
"resources": {
22+
"bullets": [
23+
{
24+
"text": "Amazon Translate API Actions List",
25+
"link": "https://docs.aws.amazon.com/translate/latest/APIReference/API_TranslateText.html"
26+
}
27+
]
28+
},
29+
"deploy": {
30+
"text": [
31+
"cdk deploy"
32+
]
33+
},
34+
"testing": {
35+
"text": [
36+
"See the GitHub repo for detailed testing instructions."
37+
]
38+
},
39+
"cleanup": {
40+
"text": [
41+
"Delete the stack: <code>cdk destroy</code>."
42+
]
43+
},
44+
"authors": [
45+
{
46+
"name": "Vaidehi Patel",
47+
"image": "https://avatars.githubusercontent.com/u/23283229?v=4",
48+
"bio": "I'm a Solutions Architect at Amazon Web Services based in Dallas,TX. I'm a serverless enthusiast, I like to build and architect serverless applications",
49+
"linkedin": "https://www.linkedin.com/in/vaidehi-patel08/"
50+
}
51+
]
52+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
aws-cdk-lib>=2.0.0
2+
constructs>=10.0.0,<11.0.0

apigw-translate-python-cdk/source.bat

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
@echo off
2+
3+
rem The sole purpose of this script is to make the command
4+
rem
5+
rem source .venv/bin/activate
6+
rem
7+
rem (which activates a Python virtualenv on Linux or Mac OS X) work on Windows.
8+
rem On Windows, this command just runs this batch file (the argument is ignored).
9+
rem
10+
rem Now we don't need to document a Windows command for activating a virtualenv.
11+
12+
echo Executing .venv\Scripts\activate.bat for you
13+
.venv\Scripts\activate.bat

apigw-translate-python-cdk/translate_api/__init__.py

Whitespace-only changes.
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
from aws_cdk import (
2+
Stack,
3+
CfnOutput,
4+
aws_iam as iam,
5+
aws_apigateway as apigateway,
6+
)
7+
from constructs import Construct
8+
9+
class TranslateApiStack(Stack):
10+
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
11+
super().__init__(scope, construct_id, **kwargs)
12+
13+
# Create IAM Role for API Gateway
14+
api_gateway_role = iam.Role(
15+
self, 'ApiGatewayIAMRole',
16+
assumed_by=iam.ServicePrincipal('apigateway.amazonaws.com'),
17+
)
18+
19+
# Add policy to the role
20+
api_gateway_role.add_to_policy(
21+
iam.PolicyStatement(
22+
actions=['translate:TranslateText'],
23+
resources=['*']
24+
)
25+
)
26+
27+
# Create API Gateway
28+
api = apigateway.RestApi(
29+
self, 'TranslateApi',
30+
rest_api_name='TranslateAPI',
31+
description='API Gateway with direct integration to Amazon Translate\'s TranslateText API.',
32+
deploy_options=apigateway.StageOptions(stage_name='Prod')
33+
)
34+
35+
# Create /translate resource
36+
translate_resource = api.root.add_resource('translate')
37+
38+
# Add POST method with AWS integration
39+
translate_resource.add_method(
40+
'POST',
41+
apigateway.AwsIntegration(
42+
service='translate',
43+
action='TranslateText',
44+
integration_http_method='POST',
45+
options=apigateway.IntegrationOptions(
46+
credentials_role=api_gateway_role,
47+
request_templates={
48+
'application/json': '''{
49+
"Text": $input.json('$.text'),
50+
"SourceLanguageCode": $input.json('$.sourceLanguageCode'),
51+
"TargetLanguageCode": $input.json('$.targetLanguageCode')
52+
}'''
53+
},
54+
passthrough_behavior=apigateway.PassthroughBehavior.NEVER,
55+
request_parameters={
56+
'integration.request.header.Content-Type': "'application/x-amz-json-1.1'",
57+
'integration.request.header.X-Amz-Target': "'AWSShineFrontendService_20170701.TranslateText'"
58+
},
59+
integration_responses=[
60+
apigateway.IntegrationResponse(
61+
status_code='200',
62+
)
63+
]
64+
)
65+
),
66+
method_responses=[
67+
apigateway.MethodResponse(
68+
status_code='200',
69+
response_models={
70+
'application/json': apigateway.Model.EMPTY_MODEL
71+
}
72+
)
73+
]
74+
)
75+
76+
# Output the API endpoint URL
77+
CfnOutput(
78+
self, 'ApiEndpoint',
79+
value=f'{api.url}translate',
80+
description='API Gateway Endpoint URL'
81+
)

0 commit comments

Comments
 (0)