[{"data":1,"prerenderedAt":108},["ShallowReactive",2],{"snippet-integration-sns-to-lambda":3},{"id":4,"title":5,"contributors":6,"description":10,"extension":11,"gitHub":12,"introBox":15,"languages":19,"meta":28,"resources":29,"services":33,"snippets":36,"stem":104,"tags":105,"type":106,"__hash__":107},"snippets\u002Fsnippets\u002Fintegration-sns-to-lambda.json","Amazon SNS trigger to invoke a Lambda function",[7,8,9],"content\u002Fcontributors\u002Fmohammed-tomeh.json","content\u002Fcontributors\u002Fvaibhav-jain.json","content\u002Fcontributors\u002Fmajd-arbash.json","Using an Amazon SNS trigger to invoke a Lambda function","json",{"template":13},{"repoURL":14},"https:\u002F\u002Fgithub.com\u002Faws-samples\u002Fserverless-snippets\u002Ftree\u002Fmain\u002Fintegration-sns-to-lambda",{"headline":16,"text":17},"How it works",[18],"The Lambda function retrieves an SNS messages from the event parameter that it receives. The function logs the content of each message.",[20,21,22,23,24,25,26,27],"Node.js","Python",".NET","TypeScript","Ruby","Java","Rust","PHP",{},{"bullets":30},[31],{"text":10,"link":32},"https:\u002F\u002Fdocs.aws.amazon.com\u002Flambda\u002Flatest\u002Fdg\u002Fwith-sns.html",[34,35],"lambda-event-functions","sns",[37],{"title":38,"codeTabs":39},"Runtimes",[40,47,54,61,69,76,83,90,97],{"id":20,"title":41,"description":42,"snippets":43},"Usage Example with Node:","Consuming an SNS event with Lambda using JavaScript.",[44],{"language":45,"code":46},"js","exports.handler = async (event, context) =&#62; {\n  for (const record of event.Records) {\n    await processMessageAsync(record);\n  }\n  console.info(\"done\");\n};\n\nasync function processMessageAsync(record) {\n  try {\n    const message = JSON.stringify(record.Sns.Message);\n    console.log(`Processed message ${message}`);\n    await Promise.resolve(1); \u002F\u002FPlaceholder for actual async work\n  } catch (err) {\n    console.error(\"An error occurred\");\n    throw err;\n  }\n}\n",{"id":22,"title":48,"description":49,"snippets":50},"Usage Example with .NET:","Consuming an SNS event with Lambda using .NET.",[51],{"language":52,"code":53},"dotnet","using Amazon.Lambda.Core;\nusing Amazon.Lambda.SNSEvents;\n\n\n\u002F\u002F Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.\n[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]\n\nnamespace SnsIntegration;\n\npublic class Function\n{\n    public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context)\n    {\n        foreach (var record in evnt.Records)\n        {\n            await ProcessRecordAsync(record, context);\n        }\n        context.Logger.LogInformation(\"done\");\n    }\n\n    private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context)\n    {\n        try\n        {\n            context.Logger.LogInformation($\"Processed record {record.Sns.Message}\");\n\n            \u002F\u002F TODO: Do interesting work based on the new message\n            await Task.CompletedTask;\n        }\n        catch (Exception e)\n        {\n            \u002F\u002FYou can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ.\n            context.Logger.LogError($\"An error occurred\");\n            throw;\n        }\n    }\n}",{"id":23,"title":55,"description":56,"snippets":57},"Usage Example with TypeScript:","Consuming an SNS event with Lambda using TypeScript.",[58],{"language":59,"code":60},"ts","import { SNSEvent, Context, SNSHandler, SNSEventRecord } from \"aws-lambda\";\n\nexport const functionHandler: SNSHandler = async (\n  event: SNSEvent,\n  context: Context\n): Promise&#60;void&#62; =&#62; {\n  for (const record of event.Records) {\n    await processMessageAsync(record);\n  }\n  console.info(\"done\");\n};\n\nasync function processMessageAsync(record: SNSEventRecord): Promise&#60;any&#62; {\n  try {\n    const message: string = JSON.stringify(record.Sns.Message);\n    console.log(`Processed message ${message}`);\n    await Promise.resolve(1); \u002F\u002FPlaceholder for actual async work\n  } catch (err) {\n    console.error(\"An error occurred\");\n    throw err;\n  }\n}\n",{"id":62,"title":63,"description":64,"snippets":65},"Go","Usage Example with Go:","Consuming an SNS event with Lambda using Go.",[66],{"language":67,"code":68},"go","package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com\u002Faws\u002Faws-lambda-go\u002Fevents\"\n\t\"github.com\u002Faws\u002Faws-lambda-go\u002Flambda\"\n)\n\nfunc handler(ctx context.Context, snsEvent events.SNSEvent) {\n\tfor _, record := range snsEvent.Records {\n\t\tprocessMessage(record)\n\t}\n\tfmt.Println(\"done\")\n}\n\nfunc processMessage(record events.SNSEventRecord) {\n\tmessage := record.SNS.Message\n\tfmt.Printf(\"Processed message: %s\\n\", message)\n\t\u002F\u002F TODO: Process your record here\n}\n\nfunc main() {\n\tlambda.Start(handler)\n}\n",{"id":21,"title":70,"description":71,"snippets":72},"Usage Example with Python:","Consuming an SNS event with Lambda using Python.",[73],{"language":74,"code":75},"py","def lambda_handler(event, context):\n    for record in event['Records']:\n        process_message(record)\n    print(\"done\")\n\ndef process_message(record):\n    try:\n        message = record['Sns']['Message']\n        print(f\"Processed message {message}\")\n        # TODO; Process your record here\n        \n    except Exception as e:\n        print(\"An error occurred\")\n        raise e\n",{"id":24,"title":77,"description":78,"snippets":79},"Usage Example with Ruby:","Consuming an SNS event with Lambda using Ruby.",[80],{"language":81,"code":82},"ruby","def lambda_handler(event:, context:)\n  event['Records'].map { |record| process_message(record) }\nend\n\ndef process_message(record)\n  message = record['Sns']['Message']\n  puts(\"Processing message: #{message}\")\nrescue StandardError =&#62; e\n  puts(\"Error processing message: #{e}\")\n  raise\nend\n",{"id":25,"title":84,"description":85,"snippets":86},"Usage Example with Java:","Consuming an SNS event with Lambda using Java.",[87],{"language":88,"code":89},"java","package example;\n\nimport com.amazonaws.services.lambda.runtime.Context;\nimport com.amazonaws.services.lambda.runtime.LambdaLogger;\nimport com.amazonaws.services.lambda.runtime.RequestHandler;\nimport com.amazonaws.services.lambda.runtime.events.SNSEvent;\nimport com.amazonaws.services.lambda.runtime.events.SNSEvent.SNSRecord;\n\n\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class SNSEventHandler implements RequestHandler&#60;SNSEvent, Boolean&#62; {\n    LambdaLogger logger;\n\n    @Override\n    public Boolean handleRequest(SNSEvent event, Context context) {\n        logger = context.getLogger();\n        List&#60;SNSRecord&#62; records = event.getRecords();\n        if (!records.isEmpty()) {\n            Iterator&#60;SNSRecord&#62; recordsIter = records.iterator();\n            while (recordsIter.hasNext()) {\n                processRecord(recordsIter.next());\n            }\n        }\n        return Boolean.TRUE;\n    }\n\n    public void processRecord(SNSRecord record) {\n        try {\n            String message = record.getSNS().getMessage();\n            logger.log(\"message: \" + message);\n        } catch (Exception e) {\n            throw new RuntimeException(e);\n        }\n    }\n\n}\n\n\n\n",{"id":26,"title":91,"description":92,"snippets":93},"Usage Example with Rust:","Consuming an SNS event with Lambda using Rust.",[94],{"language":95,"code":96},"rust","use aws_lambda_events::event::sns::SnsEvent;\nuse aws_lambda_events::sns::SnsRecord;\nuse lambda_runtime::{run, service_fn, Error, LambdaEvent};\nuse tracing::info;\n\n\u002F\u002F Built with the following dependencies:\n\u002F\u002F  aws_lambda_events = { version = \"0.10.0\", default-features = false, features = [\"sns\"] }\n\u002F\u002F  lambda_runtime = \"0.8.1\"\n\u002F\u002F  tokio = { version = \"1\", features = [\"macros\"] }\n\u002F\u002F  tracing = { version = \"0.1\", features = [\"log\"] }\n\u002F\u002F  tracing-subscriber = { version = \"0.3\", default-features = false, features = [\"fmt\"] }\n\nasync fn function_handler(event: LambdaEvent&#60;SnsEvent&#62;) -&#62; Result&#60;(), Error&#62; {\n    for event in event.payload.records {\n        process_record(&event)?;\n    }\n    \n    Ok(())\n}\n\nfn process_record(record: &SnsRecord) -&#62; Result&#60;(), Error&#62; {\n    info!(\"Processing SNS Message: {}\", record.sns.message);\n\n    \u002F\u002F Implement your record handling code here.\n\n    Ok(())\n}\n\n#[tokio::main]\nasync fn main() -&#62; Result&#60;(), Error&#62; {\n    tracing_subscriber::fmt()\n        .with_max_level(tracing::Level::INFO)\n        .with_target(false)\n        .without_time()\n        .init();\n\n    run(service_fn(function_handler)).await\n}",{"id":27,"title":98,"description":99,"snippets":100},"Usage Example with PHP:","Consuming an SNS event with Lambda using PHP.",[101],{"language":102,"code":103},"php","&#60;?php\n\n\u002F* \nSince native PHP support for AWS Lambda is not available, we are utilizing Bref's PHP functions runtime for AWS Lambda.\nFor more information on Bref's PHP runtime for Lambda, refer to: https:\u002F\u002Fbref.sh\u002Fdocs\u002Fruntimes\u002Ffunction\n\nAnother approach would be to create a custom runtime. \nA practical example can be found here: https:\u002F\u002Faws.amazon.com\u002Fblogs\u002Fapn\u002Faws-lambda-custom-runtime-for-php-a-practical-example\u002F\n*\u002F\n\n\u002F\u002F Additional composer packages may be required when using Bref or any other PHP functions runtime.\n\u002F\u002F require __DIR__ . '\u002Fvendor\u002Fautoload.php';\n\nreturn function ($event, $context) {\n    foreach ($event[\"Records\"] as $record) {\n        processMessage($record);\n    }\n    echo \"Done!\" . PHP_EOL;\n};\n\nfunction processMessage($record)\n{\n    try {\n        $message = $record['Sns']['Message'];\n        echo \"Processed Message: {$message}\" . PHP_EOL;\n    } catch (Exception $e) {\n        echo \"Error occured: {$e-&#62;getMessage()}\" . PHP_EOL;\n        throw $e;\n    }\n}\n","snippets\u002Fintegration-sns-to-lambda",[],"Integration","qPZvhAPdzVZem1bGSbAgaFsNvwMPl4RzizvZbUhcpTE",1792578864337]