4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

APIGateway + Lambda + Comprehend でサーバーレスなWeb API を作成する

Last updated at Posted at 2020-05-02

#1.Lambda#
実行ロールにデフォルトの「管理ポリシー」に加えて、『ComprehendFullAccess』の「AWS 管理ポリシー」を付与する。
image.png

ランタイムは「python3.8」で、関数コードは以下のとおり作成。

Comprehendfunction
import json
import boto3

comprehend = boto3.client('comprehend')

def lambda_handler(event, context):
    
    input_text = "とても美味しいです!"

    response = comprehend.detect_sentiment(
        Text='input_text',
        LanguageCode='ja'
    )    
    sentiment_score = response.get('SentimentScore')
    
    return {
        'statusCode': 200,
        'body': json.dumps({
            'sentiment_score': sentiment_score
        })
    }

テスト

Response:
{
  "statusCode": 200,
  "body": "{\"sentiment_score\": {\"Positive\": 0.0013845671201124787, \"Negative\": 0.00038266877527348697, \"Neutral\": 0.9982283711433411, \"Mixed\": 4.437819825398037e-06}}"
}

Request ID:
"f916f087-d681-4d0d-b533-3a2b734ef9f4"

Function Logs:
START RequestId: f916f087-d681-4d0d-b533-3a2b734ef9f4 Version: $LATEST

#2.comprehend#

※[comprehend] を参考にへLambda functionを編集する。 (https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/comprehend.html#Comprehend.Client.detect_sentiment)

Comprehendfunction
import json
import boto3

comprehend = boto3.client('comprehend')

def lambda_handler(event, context):
    
    input_text = event['queryStringParameters']['input_text']

    response = comprehend.detect_sentiment(
        Text='input_text',
        LanguageCode='ja'
    )    
    sentiment_score = response.get('SentimentScore')
    
    return {
        'statusCode': 200,
        'body': json.dumps({
            'sentiment_score': sentiment_score
        })
    }

#3.APIGateway#

APIGatewayを作成し、デプロイし、動作を確認する。

スクリーンショット 2020-04-28 18.43.09.png

(例)
https://**********.execute-api.ap-northeast-1.amazonaws.com/dev/comprehend/?input_text=最高です

以下の通り結果が表示される。

{"sentiment_score": {"Positive": 0.0013845671201124787, "Negative": 0.00038266877527348697, "Neutral": 0.9982283711433411, "Mixed": 4.437819825398037e-06}}
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?