Swiftpack.co - Package - swift-aws/aws-sdk-swift


Swift 5.1

AWS SDK for the Swift programming language working on Linux, macOS and iOS. This library provides access to all AWS services. The service APIs it provides are a direct mapping of the REST APIs Amazon publishes for each of its services.

The library consists of three parts

  1. aws-sdk-swift-core which does all the core request encoding and signing, response decoding and error handling.
  2. The service api files which define the individual AWS services and their commands with their input and output structures.
  3. The CodeGenerator which builds the service api files from the JSON model files supplied by Amazon.


Swift Package Manager

AWSSDKSwift uses the Swift Package Manager to manage its code dependencies. To use AWSSDKSwift in your codebase it is recommended you do the same. Add a dependency to the package in your own Package.swift dependencies.

    dependencies: [
        .package(name: "AWSSDKSwift", url: "https://github.com/swift-aws/aws-sdk-swift.git", from: "4.0.0")

Then add target dependencies for each of the AWSSDKSwift targets you want to use.

    targets: [
        .target(name: "MyAWSApp", dependencies: [
            .product(name: "S3", package: "AWSSDKSwift"),
            .product(name: "SES", package: "AWSSDKSwift"),
            .product(name: "IAM", package: "AWSSDKSwift")

If you are using one of the v5.0.0 pre-releases then the name parameter in the package dependencies is unnecessary, the package parameter of the target dependencies is aws-sdk-swift instead of AWSSDKSwift and also all the target names are prefixed with AWS.

Alternatively if you are using Xcode 11+ you can use the Swift Package integration and add a dependency to AWSSDKSwift through that.


AWSSDKSwift works on Linux, macOS and iOS. Version 4 is dependent on version 2 of swift-nio. Libraries/frameworks that are dependent on an earlier version of swift-nio will not work with version 4 of AWSSDKSwift. In this case Version 3 can be used. For example Vapor 3 uses swift-nio 1.13 so you can only use versions 3.x of AWSSDKSwift with Vapor 3. Below is a compatibility table for versions 3 and 4 of AWSSDKSwift.

| Version | Swift | MacOS | iOS | Linux | Vapor | |---------|-------|-------|--------|--------------------|--------| | 3.x | 4.2 - | ✓ | | Ubuntu 14.04-18.04 | 3.0 | | 4.x | 5.0 - | ✓ | 12.0 - | Ubuntu 14.04-18.04 | 4.0 |

Configuring Credentials

Before using the SDK, you will need AWS credentials to sign all your requests. Credentials can be provided to the library in the following ways.

Via EC2 Instance Profile

If you are running your code on an AWS EC2 instance, you can setup an IAM role as the server's Instance Profile to automatically grant credentials via the metadata service.

There are no code changes or configurations to specify in the code, it will automatically pull and use the credentials.

Via ECS Container credentials

If you are running your code as an AWS ECS container task, you can setup an IAM role for your container task to automatically grant credentials via the metadata service.

Similar to the EC2 setup there are no code changes or configurations to specify in the code, it will automatically pull and use the credentials.

Load Credentials from shared credential file.

You can set shared credentials in the home directory for the user running the app, in the file ~/.aws/credentials,

aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY

Load Credentials from Environment Variable

Alternatively, you can set the following environment variables:


Pass the Credentials to the AWS Service struct directly

All of the AWS Services's initializers accept accessKeyId and secretAccessKey

let ec2 = EC2(
    accessKeyId: "YOUR_AWS_ACCESS_KEY_ID",
    secretAccessKey: "YOUR_AWS_SECRET_ACCESS_KEY"

Without Credentials

Some services like CognitoIdentityProvider don't require credentials to access some of their functionality. In this case explicitly set accessKeyId and secretAccessKey to "". This will disable all other credential access functions and send requests unsigned.

Using AWSSDKSwift

AWS Swift Modules can be imported into any swift project. Each module provides a service struct that can be initialized with AWS credentials, if required, AWS region, and some configuration options. This struct contains the instance methods that correspond to the AWS service REST apis. See documentation for details on specific services.

Each aws-sdk-swift command returns a swift-nio EventLoopFuture. An EventLoopFuture is not the response of the command, but rather a container object that will be populated with the response sometime later. In this manner calls to AWS do not block the main thread. It is recommended you familiarise yourself with the swift-nio documentation, specifically EventLoopFuture if you want to take full advantage of aws-sdk-swift.

The recommended manner to interact with EventLoopFutures is chaining. The following function returns an EventLoopFuture that creates an S3 bucket, puts a file in the bucket, reads the file back from the bucket and finally prints the contents of the file. Each of these operations are chained together. The output of one being the input of the next.

import S3 //ensure this module is specified as a dependency in your package.swift

let bucket = "my-bucket"

let s3 = S3(accessKeyId: "Your-Access-Key", secretAccessKey: "Your-Secret-Key", region: .uswest2)

func createBucketPutGetObject() -> EventLoopFuture<S3.GetObjectOutput> {
    // Create Bucket, Put an Object, Get the Object
    let createBucketRequest = S3.CreateBucketRequest(bucket: bucket)

        .flatMap { response -> EventLoopFuture<S3.PutObjectOutput> in
            // Upload text file to the s3
            let bodyData = "hello world".data(using: .utf8)!
            let putObjectRequest = S3.PutObjectRequest(acl: .publicRead, body: bodyData, bucket: bucket, contentLength: Int64(bodyData.count), key: "hello.txt")
            return s3.putObject(putObjectRequest)
        .flatMap { response -> EventLoopFuture<S3.GetObjectOutput> in
            let getObjectRequest = S3.GetObjectRequest(bucket: bucket, key: "hello.txt")
            return s3.getObject(getObjectRequest)
        .whenSuccess { response in
            if let body = response.body {
                print(String(data: body, encoding: .utf8)!)

HTTP client (v5.x.x)

The AWS SDK sets up its own HTTP client for communication with AWS but you are also able to provide your own as long as it conforms to the protocol AWSHTTPClient. If you don't provide a client the SDK uses one of two different HTTP clients depending on what platform you are running on. We have extended the swift server AsyncHTTPClient so it conforms with AWSHTTPClient. This is the default client if you are running on Linux or macOS 10.14 and earlier. AsyncHTTPClient is not available on iOS. We have also supplied are own client NIOTSHTTPClient which uses NIO Transport Services and the Apple Network framework. This is the default client if you are running on iOS or macOS 10.15 and later. NIOTSHTTPClient is not available on Linux or versions of macOS earlier than 10.15.

You can provide your own HTTP client as follows

let s3 = S3(region:.uswest2, httpClientProvider: .shared(myHTTPClient))

Reasons you might want to provide your own client.

  • You have one HTTP client you want to use across all your systems.
  • You want to provide a client that is using a global EventLoopGroup.
  • On macOS you want to force the usage of the swift server AsyncHTTPClient regardless of OS version.
  • You want to change the configuration for the HTTP client used.
  • You want to provide your own custom built HTTP client.

Using AWSSDKSwift with Vapor

Integration with Vapor is pretty straight forward. Although be sure you use the correct version of AWSSDKSwift depending on which version of Vapor you are using. See the compatibility section for details. Below is a simple Vapor 3 example that extracts an email address, subject and message from a request and then sends an email using these details. Take note of the hopTo(eventLoop:) call. If your AWS SDK is not working off the same EventLoopGroup as the Vapor Request this is a requirement.

import Vapor
import HTTP
import SES

let client = SES(region: .uswest1)

final class MyController {
    struct EmailData: Content {
        let address: String
        let subject: String
        let message: String
    func sendUserEmailFromJSON(_ req: Request) throws -> EventLoopFuture<HTTPStatus> {
        return try req.content.decode(EmailData.self)
            .flatMap { (emailData)->EventLoopFuture<SES.SendEmailResponse> in
                let destination = SES.Destination(toAddresses: [emailData.address])
                let message = SES.Message(body:SES.Body(text:SES.Content(data:emailData.message)), subject:SES.Content(data:emailData.subject))
                let sendEmailRequest = SES.SendEmailRequest(destination: destination, message: message, source:"awssdkswift@me.com")

                return client.sendEmail(sendEmailRequest)
            .hopTo(eventLoop: req.eventLoop)
            .map { response -> HTTPResponseStatus in
                return HTTPStatus.ok


Visit the aws-sdk-swift documentation to browse the api reference. As there is a one-to-one correspondence with AWS REST api calls and the aws-sdk-swift api calls, you can also use the official AWS documentation for more detailed information about aws-sdk-swift commands.

upgrading from <3.0.x

The simplest way to upgrade from an existing 1.0 or 2.0 implementation is to call .wait() on existing synchronous calls. However it is recommend to rewrite your synchronous code to work with the returned future objects. It is no longer necessary to use a DispatchQueue.


AWSSDKSwift is released under the Apache License, Version 2.0. See LICENSE for details.


Stars: 356

Used By

Total: 0


v5.0.0 Alpha 5.0 - 2020-07-06 07:41:49

Using v5.0.0-alpha.5 of aws-sdk-swift-core. Sync service models to v1.33.1 of aws-sdk-go.

  • Add new targets for services CodeArtifact, Honeycode

Major version changes:

  • Split AWSClient away from services. Instead of services owning an AWSClient they are provided one in their init. This means you can have one AWSClient being used by many services. Ideally your application would have one AWSClient constructed at initialisation which is used by all the AWS services you create. PR #328 from @Ro-M, PR #330
  • Added CredentialProvider protocol which defines a method of acquiring AWS credentials. AWSClient is initialised with a CredentialProviderFactory which creates a CredentialProvider once the AWSClient is initialised. Possible credential provider factories are static: provide credentials directly, environment: from environment variables, ec2: from EC2 metadata, ecs: from ECS metadata, configFile: from ~/.aws/credentials file, empty: no credentials or selector: choose from a list of credential providers. If you don't provide a CredentialProvider the default is .selector(.environment, .ecs, .ec2, .configFile()).
  • Remove AWSMemberEncoding.encoding. Raw payload flag is now OptionSet entry PayloadOptions.raw. PR #318

Minor version changes:

  • Generate streaming versions of commands that can stream the response payload eg S3.getObjectStreaming. PR #268

Patch version changes:

  • Use Localstack single service for tests. PR #300
  • Use new AWSXML library
  • Use -enable-test-discovery for tests. PR #320
  • Don't output partition endpoint for "regionalized services". Affects only S3. If S3 service is created without region defined it finds the region from AWS_DEFAULT_REGION environment variable if it exists. Previously would be set to .useast1. PR #323
  • Replace all Node.js scripts with swift scripts. Latest version swift-sh is required to run these scripts. Use mint to install swift-sh as Homebrew version is not up to date. PR #324

Service specific changes:

  • CloudTrail: Patch request timestamps to use epoch time
  • DynamoDB: AttributeValue is now an enum with associated values. PR #309
  • S3: Cleanup path when using an endpoint. rg Remove double "//", "/" prefix. PR #307
  • S3: Fix CopyObjectRequest validation to allow copySource of format "bucket/key". PR #312
  • S3: Add support for SelectObjectContent event streams. PR #268
  • S3: Add usEast1 to enum BucketLocationConstraint

Code Generator:

  • Add PatchKeyPath1, PatchKeyPath2, PatchKeyPath3, PatchKeyPath4 to generalise the patching operations. PR #313
  • Add comment with documentationUrl whenever it exists in models. PR #321

v4.7.0 - 2020-06-02 15:24:28

Using v4.6.0 of aws-sdk-swift-core. Sync service models to v1.31.8 of aws-sdk-go.

  • Add new targets for services Synthetics and IoTSitewise
  • S3: Response metadata fixup is now case insensitive. PR #305

v5.0.0 Alpha 4.0 - 2020-05-21 10:07:13

Using v5.0.0-alpha.4 of aws-sdk-swift-core. Sync service models to v1.31.2 of aws-sdk-go.

Major version changes:

  • Payloads in response shapes are represented using AWSPayload instead of Data. PR #281
  • Use propertyWrappers to define how collections are encoded in XML and queries. PR #255
  • Added access to china and government regions and partitions of AWS. Added partition parameter to service initialiser for when a service does not require a region but still needs to define which partition is being used. PR #276
  • Add retryPolicy parameter to service initialisation, to control how the AWSClient attempts retries on failed requests. PR #296
  • Add flags to indicate when streaming request payloads is available. PR #288

Minor version changes:

  • Add new services Synthetics and IoTSiteWise.
  • Add TimeStampCoders to TimeStamps where a specific format is specified in the json model file. PR #289

Patch changes:

  • Added swift nightly build checks for Ubuntu 20.04, CentOS and AmazonLinux2. PR #287

Service specific changes:

  • CloudSearchDomain: fixed issue where Content-Type header was being overwritten
  • EC2: fixed issue where query parameters were not getting serialised correctly.
  • S3: use on: EventLoop parameter in multipart upload/download.
  • SQS: remove optional array patch from SQS.SendMessageBatch now the empty XML arrays decode correctly. PR #290

v4.6.0 - 2020-05-01 14:57:27

Using v4.5.0 of aws-sdk-swift-core

  • Sync service model files to v1.30.18 of aws-sdk-go.
  • Added regions af-south-1 and eu-south-1

v5.0.0 Alpha 3.0 - 2020-05-01 16:35:25

Using v5.0.0-alpha.3.2 of aws-sdk-swift-core. Sync service models to v1.30.18 of aws-sdk-go.

Major version changes:

  • Allow user to set the HTTP client for AWSClient. This has replaced setting the EventLoopGroup. This means you can provide a HTTP client with your own setup. If you are using AsyncHTTPClient this includes proxy settings, response decompression and timeouts. The EventLoopGroup AWSClient uses will be the same one the HTTP client uses. PR #250
  • Add on: EventLoop parameter to all the commands to force the EventLoop AWSClient will use. This has one restriction in that the EventLoop has to come from the EventLoopGroup being used by the client. PR #273
  • Remove region parameter from services that don't require a region eg IAM. PR #278

Minor version changes:

  • Added regions eu-south-1 and af-south-1.
  • Simplified the service protocol, reducing it to an enum. PR #274
  • S3: Use NIO NonBlockingFileIO in multipart upload/download.

v5.0.0 Alpha 2.0 - 2020-04-18 08:41:38

This is the second alpha release of 5.0.0.

Using v5.0.0-alpha.2 of aws-sdk-swift-core. Sync service models to v1.30.9 of aws-sdk-go.

Major version changes:

  • Use AWSPayload object for all raw data payloads. Internally this is a NIO.ByteBuffer but it can also be initialised with Data or String. PR #257
  • Split AWSShape into AWSEncodableShape and AWSDecodableShape. Request shapes conform to AWSEncodableShape and response shapes conform to AWSDecodableShape. PR #253
  • Conform shapes with a payload to AWSShapeWithPayload. PR #253
  • Paginate token protocols have been collapsed down to one protocol AWSPaginateToken.

Minor version changes:

  • The Code Generator now uses Codable to load the json model files.
  • Added HTTP status code serialisation. Mainly affects QuickSight service

v4.5.0 - 2020-04-16 08:11:34

Using v4.4.0 of aws-sdk-swift-core

  • Sync service model files to v1.30.7 of aws-sdk-go.
  • Upped swift-nio-ssl version requirement to 2.6.0 and above

v5.0.0 Alpha 1.0 - 2020-04-04 14:00:40

This is the first alpha release of v5.0.0 of aws-sdk-swift. There will be a number of future alpha releases each which could include more breaking changes.

Using v5.0.0-alpha.1 of aws-sdk-swift-core. Sync service models to v1.30.3 of aws-sdk-go.

Major version changes:

  • All library names have been prefix with AWS. PR #225
  • Package name has been changed from AWSSDKSwift to aws-sdk-swiftto ease adding it as a dependency in swift 5.2 package files.
  • Removed AWSSDKSwift library that included all the targets. PR #229
  • Minimum required version of swift is now 5.1. This is due to including the swift-crypto package. PR #241
  • Removed s3 and glacier middleware libraries. These files are now included in core s3 and glacier libraries respectively. PR #240
  • Cleanup of AWSShapeMember arrays. Removed unnecessary fields. Renamed to AWSMemberEncoding. Only include entries for an AWSShape member when the entry has an encoding entry or the member is an AWSShape payload. This removed almost 90,000 lines of code. PR #249

Service changes:

  • Route53: We were ignoring XML namespace in operations section of json models. Fixing this fixed Route53 requests. #251

v4.4.0 - 2020-03-24 16:37:25

Using v4.3.0 of aws-sdk-swift-core

  • Added APIGateway middleware to set the "Accept" header to "application/json". If this is not done error codes are not returned correctly.
  • Added S3Control middleware to fixup the request url, without this connecting to S3Control doesn't work.

v4.3.0 - 2020-03-22 16:11:43

  • Sync service model files to v1.29.29 of aws-sdk-go.
  • IAM: Add "iamPolicy" to PolicySourceType enum. Fixes decoding of IAM.SimulatePrincipalPolicy() response.

v4.2.1 - 2020-02-11 07:49:58

  • Require SwiftNIO security updates https://github.com/apple/swift-nio/releases/tag/2.13.1 and https://github.com/apple/swift-nio-ssl/security/advisories/GHSA-9556-94c5-c3j8

v3.5.1 - 2020-02-11 07:49:29

Require SwiftNIO security update https://github.com/apple/swift-nio/releases/tag/1.14.2

v4.2.0 - 2020-02-07 16:58:39

Using v4.2.0 of aws-sdk-swift-core.

  • Sync service model files to v1.28.9 of aws-sdk-go.
  • Deprecated the typealias Future. From this point on you should use EventLoopFuture.
  • Add support for paginated results. You supply a closure to the paginated versions of commands and this is called with each block of data as it is downloaded. Commands where this is applicable have a second version with the suffix Paginator

Service changes

  • CloudFront: Removed version date from function names eg createDistributionWithTags20190326 is now createDistributionWithTags

v4.1.1 - 2020-01-18 12:38:29

  • Includes new service WAFV2.

v4.1.0 - 2020-01-17 18:08:00

Using v4.1.0 of aws-sdk-swift-core.

  • Sync service model files to v1.28.3 of aws-sdk-go.
  • Added new services AccessAnalyzer, AppConfig, AugmentedAIRuntime, CodeGuruProfiler, CodeGuruReviewer, CodeStarconnections, ComputeOptimizer, ConnectParticipant, DataExchange, Detective, EBS, ElasticInference, FraudDetector, Imagebuilder, IoTSecureTunneling, Kendra, KinesisVideoSignalingChannels, MarketplaceCatalog, MigrationHubConfig, NetworkManager, Outposts, SESV2, Schemas and TranscribeStreamingService.
  • Each service exports AWSSDKSwiftCore symbols, so no need to add an import AWSSDKSwiftCore if you have already imported an AWSSDKSwift service.
  • Use github action to automatically generate documentation on publishing a release.

Services Changes

  • SQS.SendMessageBatchResult: Fixed response parsing by making successful and failed members optional. #212
  • S3.GetObjectAcl: Fixed two issues affecting this command. If a GET request has a header then sign the headers instead of the URL and added parsing of attributes in XML decoder.


  • Use github action to run CI.
  • Using localstack to test services. There are now tests for APIGateway, DynamoDB, IAM, S3, SNS, SQS, SSM.
  • Tests can now run in parallel as each test creates its own assets.
  • Added ENDPOINT environment variables for each service tested.

v3.5.0 - 2019-11-27 23:42:17

Adam Fowler:

  • Remove switch in S3RequestMiddleware.virtualAddressFixup()
  • Don't apply virtual address to s3 buckets contain a period
  • fixes iam metadata credentials lookup on ec2 instances

v4.0.0 - 2019-11-22 11:28:47

Using v4.0.0 of aws-sdk-swift-core.

Major version changes

  • aws-sdk-swift now requires Swift 5.0 or later.
  • We are now using Swift NIO 2.x. If you are dependent on a package using Swift NIO 1.14 or earlier eg Vapor 3, do not update to this version of aws-sdk-swift-core.


  • Sync service model files to v1.25.32 of aws-sdk-go.
  • Re-worked HTTPClient so can work with NIO transport services. Because of this work aws-sdk-swift now works on iOS.
  • Service classes have a EventLoopGroupProvider parameter, an enum with which you can provide your own eventLoopGroup for aws-sdk-swift to use.
  • If service struct is initialised with accessKeyId and secretAccessKey set to "" then requests are sent to AWS unsigned. This gives access to AWS services such as CognitoIdentityProvider without access credentials.
  • Added multipart upload and download from S3.

Bug fixes

  • Fixed issue with incorrect error types being thrown for some services.
  • S3: Fixed uploading to S3 with a filename containing spaces.
  • S3: Buckets containing a period do not use virtual addressing anymore. Removed validation saying you cannot use bucket names containing a period.
  • ComprehendMedical: Added dxName case to EntitySubType enum.

v3.3.0 - 2019-10-14 13:17:59

Using v3.4.0 of aws-sdk-swift-core

  • Sync service model files to v1.25.11 of aws-sdk-go.
  • Fixed issue compiling with Swift 5.1 on Linux.
  • Add validation of s3 bucket names to ensure they don't contain periods. As we use s3 bucket virtual addressing bucket names containing periods do not work.

v3.2.0 - 2019-09-17 07:07:45

Using v3.3.0 of aws-sdk-swift-core

  • Sync service model files to v1.23.12 of aws-sdk-go.
  • We are now using Stencil to generate our swift service files from the AWS model files.
  • Deprecated api commands are now marked deprecated in swift.
  • Output xml namespace as member of AWSShape where available
  • Added validation code for AWSShape members wherever it is supplied in the model files. Will validate min, max values for numbers, string and collection length and validate strings against regex patterns.
  • Autogenerate idempotency tokens.
  • Remove all AWSShape's not tagged as an input or output of an api function.
  • Stop partition endpoint overwriting the region endpoint where a default value is being used for the region endpoint.
  • let client: AWSClient in service classes is now public.
  • Using Int instead of Int32 in service files.
  • Include sessionToken in service init() functions to allow for access to services via tokens returned from STS.
  • Include middlewares in service init() functions to allow user access to requests and responses as they are processed.
  • Errors thrown by service files all conform to CustomStringConvertible.
  • API functions are not tagged as throwing anymore.

Service changes

  • S3 Add additional regions to BucketLocationConstraint enum.
  • S3 Fixup response from GetBucketLocation so it is parsed correctly.
  • S3 Don't attempt to setup virtual bucket addresses for non amazon endpoints.
  • S3 Support metadata headers for Get/Put/HeadObject
  • Route53 Make Marker optional in ListHealthChecksResponse, ListHostedZonesResponse and ListReusableDelegationSetsResponse.
  • CloudFront Capitalized HttpVersion enum entries.

v3.1.0 - 2019-07-19 01:18:52

Adam Fowler: CodeGenerator now adds CollectionEncoding enum Add more AWS services Fix Backup and DirectoryService frameworks name clash Add an issue template Patch PlatformValues enum in ec2 Deal with situation where location is set to "headers"

Jonathan McAllister: move the code generator out of the main project. in this way any code gen dependencies are not imposed on the sdks update models to latest from sdk-go 1.20.17 set sdk to min 3.1.1

v3.0.0 - 2019-05-20 15:48:02

  • update api to return future objects
  • Supply Content-MD5 header S3 operations
  • return discardableResult Future instead of Void update jazzy stub and yaml for docs

2.0.5 - 2019-04-24 16:13:04

fix s3defaultServiceEndpoint #103 ensure param order, shapes, operations, errors and serviceEndpoints are in the same order when generating code Ensure AWSShape always has a public init function #108 update core to 2.0.1 - fixes #106 update nio to latest 1.x

2.0.4 - 2019-03-04 03:06:45

  • add apiVersion header and support for treeHash checksum header for Glacier
  • update sdk-core with fix for serializing json/xml payload_path objects
  • update nio, nio-ssl to latest

2.0.3 - 2019-01-27 14:31:01

update core with fix for path in params update nio and swiftJSON to latest versions

2.0.2 - 2019-01-27 14:30:21

sync models with aws-sdk-go@v1.15.90 update docs

2.0.0 - 2019-01-27 14:28:54

  Swift 4.2
  Separate modules for all services
  Bump up to 2.0.0-* of aws-sdk-swift-core
  Follow aws naming convention for modules #78 #86

- 2018-12-05 07:12:25

- 2018-08-07 17:09:43

- 2018-04-14 17:17:03

- 2018-04-13 13:31:09