Skip to content

Commit

Permalink
Merge pull request #1573 from pbv0/pbv-feature-apigw-lambda-comprehend
Browse files Browse the repository at this point in the history
Adding apigw-lambda-comprehend-sam pattern
  • Loading branch information
mavi888 authored Aug 21, 2023
2 parents 9a35af9 + fa73be9 commit 521128d
Show file tree
Hide file tree
Showing 5 changed files with 221 additions and 0 deletions.
98 changes: 98 additions & 0 deletions apigw-lambda-comprehend-sam/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Amazon API Gateway to AWS Lambda to Amazon Comprehend

This sample project deploys an Amazon API Gateway REST API with an AWS Lambda integration. The Lambda function is written in Python, calls the Amazon Comprehend DetectSentiment API, and returns a response containing the detected sentiment.

Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/apigw-lambda-comprehend-sam

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.

## Requirements

- [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.
- [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
- [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
- [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed

## Deployment Instructions

1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
```bash
git clone https://github.com/aws-samples/serverless-patterns
```
1. Change directory to the pattern directory:
```bash
cd apigw-lambda-comprehend-sam
```
1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file:
```bash
sam deploy --guided
```
1. During the prompts:

- Enter a stack name
- Enter the desired AWS Region
- Allow SAM CLI to create IAM roles with the required permissions.

Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults.

When asked "`DetectSentimentLambdaFunction` has no authentication. Is this okay? [y/N]", answer explicitly with y for the purposes of this sample application. As a result, anyone will be able to call this example REST API without any form of authentication.

For production applications, you should [enable authentication for the API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html) using one of several available options and [follow the API Gateway security best practices](https://docs.aws.amazon.com/apigateway/latest/developerguide/security-best-practices.html).

1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing.

## How it works

This sample project uses Amazon Comprehend's DetectSentiment API by exposing it through a serverless REST API.
Here's a breakdown of the steps:

1. **Amazon API Gateway**: Receives the HTTP POST request containing text for sentiment analysis.

1. **AWS Lambda**: Triggered by the API Gateway, this function forwards the text to Amazon Comprehend's DetectSentiment API.
1. **Amazon Comprehend**: Analyzes the text, determining sentiments like "POSITIVE", "NEGATIVE", etc., and returns this analysis to Lambda.
1. **Response**: Lambda processes the Comprehend output and sends it back to the user via the API Gateway.
## Testing
Test the deployed sentiment analysis API by providing an input with a positive sentiment. You can use [curl](https://curl.se/) to send a HTTP POST request to the API. Make sure to replace the API endpoint URL with the one from your AWS SAM outputs:
```bash
curl -d '{"input": "I love strawberry cake!"}' -H 'Content-Type: application/json' https://<API Gateway endpoint>.execute-api.<AWS Region>.amazonaws.com/Prod/detect_sentiment/
```
The API returns a response that contains the detected sentiment and a confidence score for all available sentiments:
```json
{
"sentiment": "POSITIVE",
"confidence_scores": {
"Positive": 0.9991476535797119,
"Negative": 9.689308353699744e-5,
"Neutral": 0.0006526037468574941,
"Mixed": 0.00010290928184986115
}
}
```
Try testing the API with an input containing a negative sentiment and compare the results:
```bash
curl -d '{"input": "I hate chocolate cake!"}' -H 'Content-Type: application/json' https://<API Gateway endpoint>.execute-api.<AWS Region>.amazonaws.com/dev/detect_sentiment/
```
## Cleanup
To delete the resources deployed to your AWS account via AWS SAM, run the following command:
```bash
sam delete
```
---
Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
51 changes: 51 additions & 0 deletions apigw-lambda-comprehend-sam/example-pattern.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"title": "Lambda to Comprehend using REST API",
"description": "REST API backed by a Lambda function that invokes the Comprehend DetectSentiment API.",
"language": "Python",
"level": "100",
"framework": "SAM",
"introBox": {
"headline": "How it works",
"text": [
"This sample project deploys an Amazon API Gateway REST API with an AWS Lambda integration.",
"The Lambda function is written in Python, calls the Amazon Comprehend DetectSentiment API, and returns a response containing the detected sentiment."
]
},
"gitHub": {
"template": {
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-lambda-comprehend-sam",
"templateURL": "serverless-patterns/apigw-lambda-comprehend-sam",
"projectFolder": "apigw-lambda-comprehend-sam",
"templateFile": "apigw-lambda-comprehend-sam/template.yaml"
}
},
"resources": {
"bullets": [
{
"text": "Lambda to Comprehend - Serverless Pattern",
"link": "https://serverlessland.com/patterns/lambda-comprehend"
}
]
},
"deploy": {
"text": ["sam deploy --guided"]
},
"testing": {
"text": ["See the GitHub repo for detailed testing instructions."]
},
"cleanup": {
"text": ["Delete the stack: <code>sam delete</code>."]
},
"authors": [
{
"name": "Pascal Vogel",
"image": "https://avatars.githubusercontent.com/u/100202393?v=4",
"bio": "Pascal Vogel is a Solutions Architect at Amazon Web Services (AWS)."
},
{
"name": "Diana Cheng",
"image": "https://avatars.githubusercontent.com/u/248259?v=4",
"bio": "Diana Cheng is a Senior Solutions Architect at Amazon Web Services (AWS)."
}
]
}
Empty file.
30 changes: 30 additions & 0 deletions apigw-lambda-comprehend-sam/src/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import json
import boto3

# Create a client for Amazon Comprehend
comprehend = boto3.client("comprehend")


def lambda_handler(event, context):
# Extract the request body from the event object
body = json.loads(event["body"])

# Extract the input string from the request body
input_string = body["input"]

# Call the Comprehend DetectSentiment API
prediction = comprehend.detect_sentiment(Text=input_string, LanguageCode="en")

# Extract the sentiment from the response
sentiment = prediction["Sentiment"]

# Extract the confidence level from the response
confidence_scores = prediction["SentimentScore"]

# Return the results to Amazon API Gateway
return {
"statusCode": 200,
"body": json.dumps(
{"sentiment": sentiment, "confidence_scores": confidence_scores}
),
}
42 changes: 42 additions & 0 deletions apigw-lambda-comprehend-sam/template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
sentiment-analysis
Sample SAM template for sentiment analysis with AWS Lambda and Amazon Comprehend
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 5
MemorySize: 256

Resources:
DetectSentimentApi:
Type: AWS::Serverless::Api
Properties:
StageName: dev

DetectSentimentLambdaFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: src/
Handler: app.lambda_handler
Runtime: python3.9
Architectures:
- arm64
Policies:
- ComprehendBasicAccessPolicy: {}
Events:
SentimentAnalysis:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /detect_sentiment
Method: post
RestApiId:
Ref: DetectSentimentApi

Outputs:
SentimentAnalysisAPI:
Description: "API Gateway endpoint URL for the dev stage of the Detect Sentiment API"
Value: !Sub "https://${DetectSentimentApi}.execute-api.${AWS::Region}.amazonaws.com/dev/detect_sentiment/"

0 comments on commit 521128d

Please sign in to comment.