💬

【AWS学習記録3回目】サーバーレスアーキテクチャで翻訳 Web API を構築する

2024/03/03に公開

概要

学習で、サーバーレスアーキテクチャで翻訳 Web API を構築するハンズオンをやってみました!

CloudFormation

AWSTemplateFormatVersion: 2010-09-09
Resources:  
  #======================
  # RestApi
  #======================
  RestApi:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: RestApi
  
  #======================
  # Resource
  #======================
  Resource:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId: !GetAtt RestApi.RootResourceId
      PathPart: translate
      RestApiId: !Ref RestApi
  
  #======================
  # Method
  #======================
  Method:
    Type: AWS::ApiGateway::Method
    Properties:
      AuthorizationType: NONE
      HttpMethod: GET
      Integration:
        IntegrationHttpMethod: POST
        Type: AWS_PROXY
        Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Function.Arn}/invocations
        RequestParameters: 
          integration.request.querystring.input_text: method.request.querystring.input_text
      RequestParameters: 
        method.request.querystring.input_text: true
      ResourceId: !Ref Resource
      RestApiId: !Ref RestApi
  
  #======================
  # Permission
  #======================
  Permission:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName: !Ref Function  
      Principal: apigateway.amazonaws.com
  
  #======================
  # Stage
  #======================
  Stage:
    Type: AWS::ApiGateway::Stage
    Properties:
      DeploymentId: !Ref Deployment
      MethodSettings: 
        - HttpMethod: GET
          ResourcePath: /translate
      RestApiId: !Ref RestApi
  
  #======================
  # Deployment
  #======================
  Deployment:
    DependsOn: Method
    Type: AWS::ApiGateway::Deployment
    Properties:   
      RestApiId: !Ref RestApi
  
  #======================
  # Function
  #======================
  Function:
    Type: AWS::Lambda::Function
    Properties:
      Role: !GetAtt Role.Arn
      Runtime: python3.12
      FunctionName: Function
      Handler: index.lambda_handler
      Code:
        ZipFile: !Sub |
          import json
          import boto3
          import datetime

          translate = boto3.client('translate')
          dynamodb_translate_history_tbl = boto3.resource('dynamodb').Table('translate-history')

          def lambda_handler(event, context):
              input_text = event['queryStringParameters']['input_text']
              response = translate.translate_text(
                  Text=input_text,
                  SourceLanguageCode='ja',
                  TargetLanguageCode='en',
              )
              output_text = response.get('TranslatedText')
              dynamodb_translate_history_tbl.put_item(
                  Item={
                    'timestamp': datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
                    'input_text': input_text,
                    'output_text': output_text
                  }
              )
              return {
                  'statusCode': 200,
                  'body': json.dumps({
                      'output_text': output_text
                  }),
                  'isBase64Encoded': False,
                  'headers': {}
              }

  #======================
  # Role
  #======================
  Role:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument: 
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/TranslateFullAccess
        - arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess
      Policies:
        - PolicyName: ECSContainerInstancePermissions
          PolicyDocument: 
            Version: "2012-10-17"
            Statement: 
            - Effect: "Allow"
              Action: "logs:CreateLogGroup"
              Resource: "arn:aws:logs:ap-northeast-1:[アカウントID]:*"
            - Effect: "Allow"
              Action: 
              - "logs:CreateLogStream"
              - "logs:PutLogEvents"
              Resource: 
              - "arn:aws:logs:ap-northeast-1:[アカウントID]:log-group:/aws/lambda/translate-function:*"
  
  #======================
  # Table
  #======================
  Table:
    Type: AWS::DynamoDB::Table
    Properties:
      AttributeDefinitions:
        - AttributeName: timestamp
          AttributeType: S
      KeySchema: 
        - AttributeName: timestamp
          KeyType: HASH
      ProvisionedThroughput: 
        ReadCapacityUnits: 1
        WriteCapacityUnits: 1
      TableName: translate-history

参考文献

https://pages.awscloud.com/JAPAN-event-OE-Hands-on-for-Beginners-Serverless-1-2022-reg-event.html?trk=aws_introduction_page

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/translate.html

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/translate/client/translate_text.html

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/table/index.html

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/table/put_item.html

Discussion