This PR adds support for exposing Swift OpenAPI Lambda functions behind
an Application Load Balancer (ALB), providing an alternative to API
Gateway for HTTP routing to Lambda functions.
## Changes
### New ALB Support
- **OpenAPILambdaALB Protocol**: New protocol for ALB integration
alongside existing API Gateway support
- **ALB Event Handling**: Added `ALBTargetGroupRequest` and
`ALBTargetGroupResponse` support
- **HTTP Request Conversion**: Extension methods to convert ALB events
to/from HTTP requests/responses
### Core Library Updates
- **ALB-related source files**: New `/Sources/ALB/` directory with
ALB-specific implementations
- **Event Type Support**: Support for `ALBTargetGroupRequest` events
from Elastic Load Balancing
- **Response Mapping**: Proper mapping from OpenAPI responses to ALB
target group responses
### Complete ALB Example
- **QuoteAPI ALB Example**: Full working example in
`Examples/quoteapi-alb/`
- **Infrastructure as Code**: Complete SAM template with VPC, subnets,
security groups, and ALB
- **Build System**: Makefile and Docker build support for ALB deployment
- **Documentation**: Comprehensive README with ALB-specific deployment
instructions
### Key Files Added
```
Sources/ALB/
├── OpenAPILambdaALB.swift
└── ALBTargetGroup+HTTPRequest.swift
Examples/quoteapi-alb/
├── Package.swift
├── template.yaml
├── Makefile
├── README.md
├── Sources/QuoteAPI/QuoteService.swift
├── Sources/QuoteAPI/openapi.yaml
├── Sources/QuoteAPI/openapi-generator-config.yaml
└── events/GetQuote.json
```
## Usage
### Simple ALB Integration
```swift
@main
struct QuoteServiceALBImpl: APIProtocol, OpenAPILambdaALB {
func register(transport: OpenAPILambdaTransport) throws {
try self.registerHandlers(on: transport)
}
static func main() async throws {
let service = QuoteServiceALBImpl()
try await service.run()
}
// Your OpenAPI implementation...
}
```
### Key Differences from API Gateway
- Uses `OpenAPILambdaALB` instead of `OpenAPILambdaHttpApi`
- Handles `ALBTargetGroupRequest` events instead of
`APIGatewayV2Request`
- Returns `ALBTargetGroupResponse` instead of `APIGatewayV2Response`
- Requires VPC infrastructure (included in SAM template)
- No built-in authorization (implement via custom middleware if needed)
## Benefits
- **Cost Optimization**: ALB can be more cost-effective for high-traffic
applications
- **VPC Integration**: Native VPC support for private network access
- **Load Balancing**: Advanced load balancing features and health checks
- **WebSocket Support**: Future WebSocket support through ALB
- **Flexibility**: Choice between API Gateway and ALB based on use case
## Testing
- ✅ ALB example builds successfully with `sam build`
- ✅ Local testing with `sam local invoke`
- ✅ Complete infrastructure deployment via SAM
- ✅ HTTP requests properly routed through ALB to Lambda
- ✅ OpenAPI specification compatibility maintained
## Deployment
Deploy the ALB example:
```bash
cd Examples/quoteapi-alb
sam build && sam deploy --guided
```
Test the deployed endpoint:
```bash
curl http://[alb-dns-name]/stocks/AAPL
```
## Backward Compatibility
This is a purely additive change:
- Existing API Gateway implementations continue to work unchanged
- No breaking changes to existing APIs
- New ALB support is opt-in via protocol conformance
QuoteAPI
This application illustrates how to deploy a Server-Side Swift workload on AWS using the AWS Serverless Application Model (SAM) toolkit. The workload is a simple REST API that returns a string from an Amazon API Gateway. Requests to the API Gateway endpoint are handled by an AWS Lambda Function written in Swift.
Prerequisites
To build this sample application, you need:
- AWS Account
- AWS Command Line Interface (AWS CLI) - install the CLI and configure it with credentials to your AWS account
- AWS SAM CLI - a command-line tool used to create serverless workloads on AWS
- Docker Desktop - to compile your Swift code for Linux deployment to AWS Lambda
Build the application
The sam build command uses Docker to compile your Swift Lambda function and package it for deployment to AWS.
sam build
On macOS, you might need to run this command if sam doesn't see docker:
export DOCKER_HOST=unix://$HOME/.docker/run/docker.sock
Deploy the application
The sam deploy command creates the Lambda function and API Gateway in your AWS account.
sam deploy --guided
The project creates an API endpoint protected by a bearer token authorization. Use token value '123' while testing. Youc an change the token validation logic in the LambdaAuthorizer function. To learn more about Lambda authorizer function, refer to the API Gateway documentation.
Use the API
At the end of the deployment, SAM displays the endpoint of your API Gateway:
Outputs
----------------------------------------------------------------------------------------
Key SwiftAPIEndpoint
Description API Gateway endpoint URL for your application
Value https://[your-api-id].execute-api.[your-aws-region].amazonaws.com
----------------------------------------------------------------------------------------
Use cURL or a tool such as Postman to interact with your API. Replace [your-api-endpoint] with the SwiftAPIEndpoint value from the deployment output.
Invoke the API Endpoint
curl -H 'Authorization: Bearer 123' https://[your-api-endpoint]/stocks/AMZN
Test the API Locally
SAM also allows you to execute your Lambda functions locally on your development computer. Follow these instructions to execute the Lambda function locally. Further capabilities can be explored in the SAM Documentation.
Event Files
When a Lambda function is invoked, API Gateway sends an event to the function with all the data packaged with the API call. When running the functions locally, you pass in a json file to the function that simulates the event data. The events folder contains a json file for the function.
Invoke the Lambda Function Locally
sam local invoke QuoteService --event events/GetQuote.json
On macOS, you might need to run this command if sam doesn't see docker:
export DOCKER_HOST=unix://$HOME/.docker/run/docker.sock
Cleanup
When finished with your application, use SAM to delete it from your AWS account. Answer Yes (y) to all prompts. This will delete all of the application resources created in your AWS account.
sam delete
⚠️ Security and Reliability Notice
This is an example application 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)
Note: The openapi.yaml file in this example is not suited for production. In real-world scenarios, you must:
- Ensure that the global security field has rules defined
- Ensure that security operations is not empty (OpenAPI Security Specification)
- Follow proper authentication, authorization, input validation, and error handling practices
As per Checkov CKV_OPENAPI_4 and CKV_OPENAPI_5 security checks.