Swift Server Implementation - RESTful APIs, AWS Lambda Serverless For Swift Runtime amazonlinux: AWS Lambda + API Gateway

Overview

swift-serverless-rest-api-aws-lambda-swift-runtime-amzlinux2-arm64


aws-lambda-swift

swift-lambda-runtime-stats

swift-serverless-aws-lambda


Swift Server Implementation - RESTful APIs, AWS Lambda Serverless For Swift Runtime amazonlinux: AWS Lambda + API Gateway deployed on Graviton arm64 build **swift:5.6.2-amazonlinux2-docker image**

Using Xcode 13+, Utilizing Latest features of Swift Programming Language
Utilizing New AsyncLambdaHandler feature to support latest structured concurrency pattern:
**"async/await"** (Swift 5.5+)
For any detail about Server-Side-Swift and Lambda-Serverless solutions, Please check [here](https://docs.google.com/document/d/1GlGv0avpbpE6lqJbpxz5iHgaiPMC5E543rYGg5Ionbw/edit?usp=sharing)



Just upload "lambda.zip" to AWS Lambda via S3 bucket file (direct lambda upload limit is 10MB)
AWS CLI command to update (IAM Role needs to be configured with required lambda & s3 permissions ):
aws lambda update-function-code --function "$lambda_function_name" --s3-bucket "$s3_bucket_name" --region=us-east-1 --s3-key lambda.zip

Test the welcome route: In Lambda Test Tab with following APIGateway Event
{ "routeKey": "GET /welcome", "version": "2.0", "rawPath": "/welcome", "requestContext": { "accountId": "", "apiId": "", "domainName": "", "domainPrefix": "", "stage": "", "requestId": "", "http": { "path": "/welcome", "method": "GET", "protocol": "HTTP/1.1", "sourceIp": "", "userAgent": "" }, "time": "", "timeEpoch": 0 }, "isBase64Encoded": false, "rawQueryString": "", "headers": {} }

GET /welcome -> json resonse -> {"message": "swift rest-api server is running"}



Set Environment variable for MongoDB Cloud database via Lambda configuration -> Environments Variables: DATABASE_URL "mongodb:url_connect_database"
We can use MongoDB Atlas Cloud managed solution - Free Shared Instance

e-Route
Connect an API gateway with entity-based Route:
[ ANY ] /api/e/{entity}
[ ANY ] /api/e/{entity}/{id}

CRUD: Any Entity as json request can be created/updated/read/deleted, to/from the MongoDB database
exp:

Make CRUD Operations simpler, with options for custom object validation. APIGateway also provide custom json object mapping for request validation
[ ANY ] /api/e/{entity}

[ POST ] /api/e/users
[ GET ] /api/e/users?sort=created_at&order=desc&limit=20
[ GET ] /api/e/users/id
[ PUT ] /api/e/users/id
[ DELETE ] /api/e/users/id

JWT Authorization:
[ POST ] /api/login -> {"access_token": "eyD7uitr4em......."}
[ GET ] /api/user/id :::: headers: { "Authorization": "Bearer eyD7uitr4em.......", "content-type": "application/json" }



  • Strongly typed feature of Swift for stable and faster development
  • Easy deployment to AWS Serverless Lambda without any server maintenance
  • Build in security by using APIGateway to access the server RESTful APIs
  • MongoDB NoSql Schema-less database integration to consume json-based services
  • No DataModeling used: So No data migration changes require when adding new (key,value) pair to a collection / table.
  • Any json can be added to any collection - completely dynamic system
  • Any custom validations can be used for any specific resources like: users,bookings, etc.

Using Swift with Lambda and AWS

AWS Lambda supports a couple programming languages natively. This means you can upload the source code directly and AWS Lambda can compile it on the fly. Unfortunately, this isn’t yet the case for Swift. So, for Swift to run on AWS Lambda, you need to:

  • Compile the function as an executable file that runs on Amazon Linux 2.
  • Include all dependencies and libraries with the bootstrap file.
  • You’ll use Docker to do that, and i have provided you with a convenient ZIP file of your function and its dependencies that you upload to AWS Lambda.
  • AWS Lambda does come with a few limitations:
  • AWS Lambda functions run for a maximum of 15 minutes.
  • A function may take a few extra seconds to run for the first time since AWS Lambda is booting the function. This is also referred to as a “cold start”.
  • AWS Lambda is, by definition, stateless; there’s no shared memory among AWS Lambda functions.
  • AWS Lambda functions can perform a variety of tasks, so not every AWS Lambda function is a public function. Depending on your use case, you may not even need internet access.
  • AWS Lambda functions can use EventLoops, but they’re usually used within a specific context only.


Working On

  • JWT authorization via:
    • APIGateway Authorizer for any specific route
    • Custom implementation is pretty much dynamic. Using JWT Library dependency but it may add an additional cold start time for boot up.

  • CI/CD for one-click/command deploy updates to Lambda func
  • Verify Apple claims in WWDC: Static Linking for Linux Optimize Lambda Performance
    • Static Linking for Linux to achieve:
      • 33% faster cold start time on AWS Lambda
      • 40% faster invocation time for APIGateway Lambda


Any Feedback, suggestion, improvisation is welcomed



Created By,
Furqan
(Software Developer / Solution Architect)
Email: [email protected]

You might also like...
Implementation of x-callback-url (Inter app communication) in swift
Implementation of x-callback-url (Inter app communication) in swift

CallbackURLKit - Inter app communication Starting to integrate URL scheme in an app, why not be compliant with x-callback-url. CallbackURLKit.register

Swift implementation of the package url spec

PackageURL Swift implementation of the package url specification. Requirements Swift 5.3+ Usage import PackageURL let purl: PackageURL = "pkg:swift/a

SwiftRedux is a Swift implementation of the Redux state container

SwiftRedux is a Swift implementation of the Redux state container. It relies on the same concepts and provides familiar Hooks through property wrappers.

Swift implementation of the QOI Format

Swift-QOI Swift implementation of the QOI Format. Contains extensions for AppKit and UIKit to integrate into your projects with ease. Documentation //

Swift implementation of the QOI Format

Swift-QOI Swift implementation of the QOI Format. Contains extensions for AppKit and UIKit to integrate into your projects with ease. Documentation //

The sample implementation of zip-archived document for a macOS AppKit platform.
The sample implementation of zip-archived document for a macOS AppKit platform.

The sample implementation of zip-archived document for a macOS AppKit platform. You can implement NSDocument-based I/O of archived document in your application like .sketch or .key.

Extensions giving Swift's Codable API type inference super powers 🦸‍♂️🦹‍♀️
Extensions giving Swift's Codable API type inference super powers 🦸‍♂️🦹‍♀️

Welcome to Codextended — a suite of extensions that aims to make Swift’s Codable API easier to use by giving it type inference-powered capabilities an

noppefoxwolf/notion is a notion.so API library written in swift.
noppefoxwolf/notion is a notion.so API library written in swift.

notion noppefoxwolf/notion is a notion.so API library written in swift. Installation Xcode Project Swift Packages [email protected]:noppefoxwolf/notion

This is a app developed in Swift, using Object Oriented Programing, UIKit user interface programmatically, API Request and Kingfisher to load remote images

iOS NOW ⭐ This is a app developed in Swift, using Object Oriented Programing, UIKit user interface programmatically, API Request and Kingfisher to loa

Owner
Furqan
Functional Backend Developer: Scala, Akka, ZIO, JVM, RESTful API's, Node.js, Typescript, Swift Backend, MongoDB, Kafka, Microservices, Serverless, AWS, Lambda
Furqan
Swift AWS Lambda to automatically assign engineers to pull requests with a Slack integration

PR Assigner A Swift AWS Lambda to automatically assign engineers to pull requests with a Slack integration. Features ??

Just Eat 28 Oct 18, 2022
Swift-compute-runtime - Swift runtime for Fastly Compute@Edge

swift-compute-runtime Swift runtime for Fastly Compute@Edge Getting Started Crea

Andrew Barba 57 Dec 24, 2022
Swift-friendly API for a set of powerful Objective C runtime functions.

ObjectiveKit ObjectiveKit provides a Swift friendly API for a set of powerful Objective C runtime functions. Usage To use ObjectiveKit: Import Objecti

Roy Marmelstein 850 Oct 25, 2022
💡 A light Swift wrapper around Objective-C Runtime

A light wrapper around Objective-C Runtime. What exactly is lumos? lumos as mentioned is a light wrapper around objective-c runtime functions to allow

Suyash Shekhar 139 Dec 19, 2022
Plugin and runtime library for using protobuf with Swift

Swift Protobuf Welcome to Swift Protobuf! Apple's Swift programming language is a perfect complement to Google's Protocol Buffer ("protobuf") serializ

Apple 4.1k Dec 28, 2022
A simple utility allowing to detect Swift version at runtime.

SwiftVersionDetector SwiftVersionDetector allows you to detect Swift version at runtime. Note that detecting the Swift version of the machine on which

Alessandro Venturini 2 Dec 3, 2022
Swift APIs for getting book information from popular web services

Swift APIs for getting book information from popular web services

Brian Dewey 1 Sep 25, 2021
swift-highlight a pure-Swift data structure library designed for server applications that need to store a lot of styled text

swift-highlight is a pure-Swift data structure library designed for server applications that need to store a lot of styled text. The Highlight module is memory-efficient and uses slab allocations and small-string optimizations to pack large amounts of styled text into a small amount of memory, while still supporting efficient traversal through the Sequence protocol.

kelvin 4 Aug 14, 2022
Ethereum Wallet Toolkit for iOS - You can implement an Ethereum wallet without a server and blockchain knowledge.

Introduction EtherWalletKit is an Ethereum Wallet Toolkit for iOS. I hope cryptocurrency and decentralized token economy become more widely adapted. H

Sung Woo Chang 136 Dec 25, 2022
Utility to run the SPI-Server tests as a benchmark

spi-benchmark This package comprises a simple tool to run the SwiftPackageIndex-Server tests in a loop, logging the run times. The purpose is to colle

Swift Package Index 2 Mar 13, 2022