Skip to content

Enhance apigw-lambda-sns pattern with production-ready improvements #2777

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion apigw-lambda-sns/api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,23 @@ paths:
application/json:
schema:
$ref: "#/components/schemas/Empty"
"400":
description: "400 response"
"500":
description: "500 response"
x-amazon-apigateway-integration:
httpMethod: "POST"
uri: "arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:LambdaFunctionName/invocations"
responses:
default:
statusCode: "200"
".*4\\d{2}.*":
statusCode: "400"
".*5\\d{2}.*":
statusCode: "500"
passthroughBehavior: "when_no_match"
contentHandling: "CONVERT_TO_TEXT"
type: "aws"
type: "aws_proxy"
components:
schemas:
Empty:
Expand Down
33 changes: 24 additions & 9 deletions apigw-lambda-sns/src/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,38 @@ def lambda_handler(event, context):
logger.setLevel(logging.INFO)
logger.info("request: " + json.dumps(event))

topic_arn = os.environ.get('TOPIC_ARN')

sns_client = boto3.client("sns")

try:
topic_arn = os.environ.get('TOPIC_ARN')
if not topic_arn:
logger.error("Missing TOPIC_ARN environment variable")
return {
"statusCode": 500,
"body": json.dumps({"error": "Server configuration error"})
}

sns_client = boto3.client("sns")
sent_message = sns_client.publish(
TargetArn=topic_arn,
Message=json.dumps({'default': json.dumps(event)})
)

if sent_message is not None:
logger.info(f"Success - Message ID: {sent_message['MessageId']}")
logger.info(f"Success - Message ID: {sent_message['MessageId']}")
return {
"statusCode": 200,
"body": json.dumps("Success")
"body": json.dumps({"status": "Success", "messageId": sent_message['MessageId']})
}

except ClientError as e:
logger.error(e)
return None
error_code = e.response['Error']['Code']
error_message = e.response['Error']['Message']
logger.error(f"ClientError: {error_code} - {error_message}")
return {
"statusCode": 500,
"body": json.dumps({"error": "Failed to publish message to SNS"})
}
except Exception as e:
logger.error(f"Unexpected error: {str(e)}")
return {
"statusCode": 500,
"body": json.dumps({"error": "Internal server error"})
}
4 changes: 2 additions & 2 deletions apigw-lambda-sns/template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Resources:
Handler: code.lambda_handler
MemorySize: 128
Timeout: 3
Runtime: python3.8
Runtime: python3.13
Environment:
Variables:
TOPIC_ARN: !Ref MySnsTopic
Expand Down Expand Up @@ -60,6 +60,6 @@ Outputs:
SNStopicARN:
Description: SNS topic ARN
Value: !Ref MySnsTopic

apiGatewayInvokeURL:
Value: !Sub https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/s1