This project is a starting point for writing an HTTP service in Swift. It contains configuration files and scripts to fully automate deploying to AWS in a matter of seconds using the Serverless Framework. It is based on samples and documentation from swift-server/swift-aws-lambda-runtime
Built with 💘 by the folks @ Stream.
In the Samples folder you can find a Chatbot sample built from this tutorial: Write a Chatbot in Swift and Deploy to AWS Lambda
Write your code in Sources/Lambda/main.swift
.
Run ./Scripts/deploy.sh
.
Open the output URL in your browser.
And done!
There is some code already present in the Sources/Lambda/main.swift
file. It simply outputs "Hello, world!" in plain text.
import AWSLambdaEvents
import AWSLambdaRuntime
import NIO
// MARK: - Run Lambda
Lambda.run(APIGatewayProxyLambda())
// MARK: - Handler, Request and Response
// FIXME: Use proper Event abstractions once added to AWSLambdaRuntime
struct APIGatewayProxyLambda: EventLoopLambdaHandler {
public typealias In = APIGateway.Request
public typealias Out = APIGateway.Response
public func handle(context: Lambda.Context, event: APIGateway.Request) -> EventLoopFuture<APIGateway.Response> {
context.logger.debug("hello, api gateway!")
return context.eventLoop.makeSucceededFuture(APIGateway.Response(statusCode: .ok, body: "Hello, world!"))
}
}
If you want to output some HTML, just set the "Content-Type" header to "text/html; charset=UTF-8"
...
return context.eventLoop.makeSucceededFuture(APIGateway.Response(
statusCode: .ok,
headers: ["Content-Type": "text/html; charset=UTF-8"],
body: """
<p align="center">
<h2 align="center"> Hello, world! From Swift 5.2 💘 </h2>
</p>
<hl/>
<p align="center">\(event.requestContext.identity.userAgent ?? "")</p>
""")
)
...
For more information on the available settings and methods, refer to the Swift AWS Lambda Runtime README
To change some characteristics of your HTTP endpoint, such as the method expected, you should modify the serverless.yml
file. For more information on the available parameters, refer to the Serverless.yml Reference.
If you have a suggestion or bug report, please file an issue in the Swift Lambda repository. If you want to take a stab at contributing code, don't hesitate in submitting a PR. Don't forget to leave a star if you liked it :)