This is a simple example of an AWS Lambda function that takes a JSON structure as an input parameter and returns a JSON structure as a response.
The runtime takes care of decoding the input and encoding the output.
The code defines HelloRequest and HelloResponse data structures to represent the input and output payloads. These structures are typically shared with a client project, such as an iOS application.
The code creates a LambdaRuntime struct. In it's simplest form, the initializer takes a function as an argument. The function is the handler that will be invoked when an event triggers the Lambda function.
The handler is (event: HelloRequest, context: LambdaContext). The function takes two arguments:
- the event argument is a
HelloRequest. It is the parameter passed when invoking the function. - the context argument is a
Lambda Context. It is a description of the runtime context.
The function return value will be encoded to a HelloResponse as your Lambda function response.
To build & archive the package, type the following commands.
swift package --allow-network-connections docker lambda-buildIf there is no error, there is a ZIP file ready to deploy.
The ZIP file is located at .build/plugins/AWSLambdaBuilder/outputs/AWSLambdaBuilder/HelloJSON/HelloJSON.zip
Here is how to deploy using the lambda-deploy plugin.
swift package --allow-network-connections all:443 lambda-deployThis creates the Lambda function, provisions the necessary IAM role, and uploads the deployment package.
To invoke the Lambda function, use this aws command line.
aws lambda invoke \
--function-name HelloJSON \
--payload $(echo '{ "name" : "Seb", "age" : 50 }' | base64) \
out.txt && cat out.txt && rm out.txtNote that the payload is expected to be a valid JSON string.
This should output the following result.
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST"
}
{"greetings":"Hello Seb. You look younger than your age."}
When done testing, you can delete the Lambda function with this command.
swift package --allow-network-connections all:443 lambda-deploy --deleteThese are example applications for demonstration purposes. When deploying such infrastructure in production environments, we strongly encourage you to follow these best practices for improved security and resiliency:
- Enable access logging on API Gateway (documentation)
- Ensure that AWS Lambda function is configured for function-level concurrent execution limit (concurrency documentation, configuration guide)
- Check encryption settings for Lambda environment variables (documentation)
- Ensure that AWS Lambda function is configured for a Dead Letter Queue (DLQ) (documentation)
- Ensure that AWS Lambda function is configured inside a VPC when it needs to access private resources (documentation, code example)