

# Getting started with the AWS SDK for Swift
<a name="getting-started"></a>

Learn how to install, set up, and use the SDK to create an application to access an AWS resource programmatically. 

**Topics**
+ [Setting up](setting-up.md)
+ [Authenticating with AWS](authenticating.md)
+ [Creating an application](simple-app.md)

# Setting up the AWS SDK for Swift
<a name="setting-up"></a>

The AWS SDK for Swift is a cross-platform, open source [Swift](https://swift.org/) package that lets applications and tools built using Swift make full use of the services offered by AWS. Using the SDK, you can build Swift applications that work with Amazon S3, Amazon EC2, DynamoDB, and more.

The SDK package is imported into your project using the [Swift Package Manager](https://swift.org/package-manager/) (SPM), which is part of the standard Swift toolchain.

When you’ve finished following the steps in this article, or have confirmed that everything is configured as described, you’re ready to begin developing using the AWS SDK for Swift.

## Overview
<a name="setup-overview"></a>

To make requests to AWS using the AWS SDK for Swift, you need the following:
+ An active AWS account.
+ A user in IAM Identity Center with permission to use the AWS services and resources your application will access.
+ A development environment with version 5.9 or later of the Swift toolchain. If you don’t have this, you’ll install it as [ part of the steps below](#setup-envtools).
+ Xcode users need version 15 or later of the Xcode application. This includes Swift 5.9.

After finishing these steps, you’re ready to use the SDK to develop Swift projects that access AWS services.

### Setting up AWS access
<a name="setup-access"></a>

Before installing the Swift tools, configure your environment to let your project access AWS services. This section covers creating and configuring your AWS account, preparing IAM Identity Center for use, and setting the environment variables used by the SDK for Swift to fetch your access credentials.

#### Sign up for an AWS account
<a name="sign-up-for-aws"></a>

If you do not have an AWS account, complete the following steps to create one.

**To sign up for an AWS account**

1. Open [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup).

1. Follow the online instructions.

   Part of the sign-up procedure involves receiving a phone call or text message and entering a verification code on the phone keypad.

   When you sign up for an AWS account, an *AWS account root user* is created. The root user has access to all AWS services and resources in the account. As a security best practice, assign administrative access to a user, and use only the root user to perform [tasks that require root user access](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks).

AWS sends you a confirmation email after the sign-up process is complete. At any time, you can view your current account activity and manage your account by going to [https://aws.amazon.com/](https://aws.amazon.com/) and choosing **My Account**.

#### Create a user with administrative access
<a name="create-an-admin"></a>

After you sign up for an AWS account, secure your AWS account root user, enable AWS IAM Identity Center, and create an administrative user so that you don't use the root user for everyday tasks.

**Secure your AWS account root user**

1.  Sign in to the [AWS Management Console](https://console.aws.amazon.com/) as the account owner by choosing **Root user** and entering your AWS account email address. On the next page, enter your password.

   For help signing in by using root user, see [Signing in as the root user](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial) in the *AWS Sign-In User Guide*.

1. Turn on multi-factor authentication (MFA) for your root user.

   For instructions, see [Enable a virtual MFA device for your AWS account root user (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html) in the *IAM User Guide*.

**Create a user with administrative access**

1. Enable IAM Identity Center.

   For instructions, see [Enabling AWS IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-set-up-for-idc.html) in the *AWS IAM Identity Center User Guide*.

1. In IAM Identity Center, grant administrative access to a user.

   For a tutorial about using the IAM Identity Center directory as your identity source, see [ Configure user access with the default IAM Identity Center directory](https://docs.aws.amazon.com//singlesignon/latest/userguide/quick-start-default-idc.html) in the *AWS IAM Identity Center User Guide*.

**Sign in as the user with administrative access**
+ To sign in with your IAM Identity Center user, use the sign-in URL that was sent to your email address when you created the IAM Identity Center user.

  For help signing in using an IAM Identity Center user, see [Signing in to the AWS access portal](https://docs.aws.amazon.com/signin/latest/userguide/iam-id-center-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

**Assign access to additional users**

1. In IAM Identity Center, create a permission set that follows the best practice of applying least-privilege permissions.

   For instructions, see [ Create a permission set](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html) in the *AWS IAM Identity Center User Guide*.

1. Assign users to a group, and then assign single sign-on access to the group.

   For instructions, see [ Add groups](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html) in the *AWS IAM Identity Center User Guide*.

#### Grant programmatic AWS account access
<a name="programmatic-access"></a>

Users need programmatic access if they want to interact with AWS outside of the AWS Management Console. The way to grant programmatic access depends on the type of user that's accessing AWS.

To grant users programmatic access, choose one of the following options.


****  

| Which user needs programmatic access? | To | By | 
| --- | --- | --- | 
| IAM | (Recommended) Use console credentials as temporary credentials to sign programmatic requests to the AWS CLI, AWS SDKs, or AWS APIs. |  Following the instructions for the interface that you want to use. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/setting-up.html)  | 
|  Workforce identity (Users managed in IAM Identity Center)  | Use temporary credentials to sign programmatic requests to the AWS CLI, AWS SDKs, or AWS APIs. |  Following the instructions for the interface that you want to use. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/setting-up.html)  | 
| IAM | Use temporary credentials to sign programmatic requests to the AWS CLI, AWS SDKs, or AWS APIs. | Following the instructions in [Using temporary credentials with AWS resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) in the IAM User Guide. | 
| IAM | (Not recommended)Use long-term credentials to sign programmatic requests to the AWS CLI, AWS SDKs, or AWS APIs. |  Following the instructions for the interface that you want to use. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/setting-up.html)  | 

For more advanced cases regarding configuring the credentials and Region, see [The .aws/credentials and .aws/config files](http://docs.aws.amazon.com/credref/latest/refdocs/creds-config-files.html), [AWS Region](http://docs.aws.amazon.com/credref/latest/refdocs/setting-global-region.html), and [Using environment variables](http://docs.aws.amazon.com/credref/latest/refdocs/environment-variables.html) in the [AWS SDKs and Tools Reference Guide](http://docs.aws.amazon.com/credref/latest/refdocs).

**Note**  
If you plan to develop a macOS desktop application, keep in mind that due to sandbox restrictions, the SDK is unable to access your `~/.aws/config` and `~/.aws/credentials` files, as there is no entitlement available to grant access to the `~/.aws` directory. See [Security and authentication when testing on macOS](#mac-sandbox) for details.

## Setting up your Swift development environment
<a name="setup-envtools"></a>

The SDK requires at least version 5.9 of Swift. This can be installed either standalone or as part of the Xcode development environment on macOS.
+ Swift 5.9 toolchain or newer.
+ If you're developing on macOS using Xcode, you need a minimum of Xcode 15.
+ An AWS account. If you don’t have one already, you can create one using the [AWS portal](https://portal.aws.amazon.com/billing/signup).

### Prepare to install Swift
<a name="installing-prep"></a>

This isn't necessary on macOS.

The Swift install process for Linux doesn't automatically install `libcrypto` version 1.1, even though it's required by the compiler. To install it, be sure to install OpenSSL 1.1 or later, as well as its development package. Using the `yum` package manager, for example:

```
$ sudo yum install openssl openssl-devel
```

Using the `apt` package manager:

```
$ sudo apt install openssl libssl-dev
```

### Installing Swift
<a name="installing-swift"></a>

On macOS, the easiest way to install Swift is to simply install Apple’s Xcode IDE, which includes Swift and all the standard libraries and tools that go with it. This can be found [on the macOS App Store](https://apps.apple.com/us/app/xcode/id497799835).

If you’re using Linux or Windows, or don’t want to install Xcode on macOS, the Swift organization’s web site has detailed instructions to [install and set up the Swift toolchain](https://swift.org/getting-started/#installing-swift).

### Checking the Swift tools version number
<a name="check-swift-version"></a>

If Swift is already installed, you can verify the version number using the command `swift --version`. The output will look similar to one of the following examples.

 **Checking the Swift version on macOS** 

```
$ swift --version
swift-driver version: 1.87.1 Apple Swift version 5.9 (swiftlang-5.9.0.128.108 clang-1500.0.40.1)
Target: x86_64-apple-macosx14.0
```

 **Checking the Swift version on Linux** 

```
$ swift --version
Swift version 5.8.1 (swift-5.8.1-RELEASE)
Target: x86_64-unknown-linux-gnu
```

For more information about the configuration and credentials files shared among the AWS Command Line Interface and the various AWS SDKs, see the [AWS SDKs and Tools Reference Guide](http://docs.aws.amazon.com/sdkref/latest/guide/).

## Adding the AWS SDK for Swift as a dependency
<a name="adding-dependency"></a>

To add AWS SDK for Swift as a dependency to your Swift package, follow the steps in [Creating a simple application using the AWS SDK for Swift](simple-app.md).

To add AWS SDK for Swift as a dependency to your Xcode project, follow the steps in [Integrating with Apple platforms using the AWS SDK for Swift](apple-integration.md).

## Security and authentication when testing on macOS
<a name="mac-sandbox"></a>

### Configuring the App Sandbox
<a name="configuring-the-app-sandbox"></a>

If your SDK for Swift project is a desktop application that you’re building in Xcode, you will need to enable the App Sandbox capability and turn on the "Outgoing Connections (Client)" entitlement so that the SDK can communicate with AWS.

First, open the macOS target’s **Signing & Capabilities** panel, shown below.

![\[Xcode project settings panel showing Signing & Capabilities tab for Supergame macOS target.\]](http://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/images/xcode-add-capability-button.png)


Click the **\$1 Capability** button near the top left of this panel to bring up the box listing the available capabilities. In this box, locate the "App Sandbox" capability and double-click on it to add it to your target.

![\[App Sandbox capability description with icon and explanation of its security function.\]](http://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/images/xcode-capability-box.png)


Next, back in your target’s **Signing & Capabilities** panel, find the new **App Sandbox** section and make sure that next to **Network**, the **Outgoing Connections (Client)** checkbox is selected in the following image.

![\[Xcode project settings showing Signing & Capabilities tab with App Sandbox options.\]](http://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/images/xcode-app-sandbox.png)


### Using AWS access keys on macOS
<a name="using-access-keys-on-macos"></a>

Although shipping applications should use AWS IAM Identity Center, Amazon Cognito Identity, or similar technologies to handle authentication instead of requiring the direct use of AWS access keys, you may need to use these low-level credentials during development and testing.

macOS security features for desktop applications don’t allow applications to access files without express user permission, so the SDK can’t automatically configure clients using the contents of the CLI’s `~/.aws/config` and `~/.aws/credentials` files. Instead, you need to use the `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` environment variables to specify the authentication keys for your AWS account.

When running projects from within Xcode, the environment you have set up for your shell is not automatically inherited. Because of this, if you want to test your code using your AWS account’s access key ID and secret access key, you need to set up the runtime environment for your application in the Xcode scheme for your development device. To configure the environment for a particular target in your Xcode project, switch to that target, then choose **Edit Scheme** in Xcode’s **Product** menu.

This will open the scheme editor window for your project. Click on the **Run** phase in the left sidebar, then **Arguments** in the tab bar near the top of the window.

![\[Run scheme editor window showing Arguments tab with AWS environment variables.\]](http://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/images/xcode-scheme-environ.png)


Under **Environment Variables**, click the **\$1** icon to add `AWS_REGION` and set its value to the desired region (in the screenshot above, it’s set to "us-east-2"). Then add `AWS_ACCESS_KEY_ID` and its value, then `AWS_SECRET_ACCESS_KEY` and its value. If you're using temporary credentials (which is recommended), also add the `AWS_SESSION_TOKEN` variable and its value. Close the window once you have these configured and your scheme’s Run configuration looks similar to the above.

**Important**  
Be sure to uncheck the **Shared** checkbox before pushing your code to any public version control repository such as GitHub. Otherwise, your AWS access key and secret access key will be *included* in the publicly shared content. This is important enough to be worth double-checking regularly.

Your project should now be able to use the SDK to connect to AWS services.

## Building and running a SwiftPM project
<a name="building-and-running-an-spm-project"></a>

To build and run a Swift Package Manager project from a Linux or macOS terminal prompt, use the following commands.

 **Build a project** 

```
$ swift build
```

 **Run a project** 

```
$ swift run
$ swift run executable-name
$ swift run executable-name arg1, ...
```

If your project builds only one executable file, you can type **swift run** to build and run it. If your project outputs multiple executables, you can specify the file name of the executable you want to run. If you want to pass arguments to the program when you run it, you *must* specify the executable name before listing the arguments.

 **Get the built product output directory** 

```
$ swift build --show-bin-path
/home/janice/MyProject/.build/x86_64-unknown-linux-gnu/debug
```

 **Delete build artifacts** 

```
$ swift package clean
```

 **Delete build artifacts and all build caches** 

```
$ swift package reset
```

## Importing AWS SDK for Swift libraries into source files
<a name="importing-sdk-for-swift-libraries-into-source-files"></a>

After the libraries are in place, you can use the Swift `import` directive to import the individual libraries into each source file that needs them. To use the functions for a given service, import its library from the AWS SDK for Swift package into your source code file. Also import the `ClientRuntime` library, which contains utility functions and type definitions.

```
import Foundation
import ClientRuntime
import AWSS3
```

The standard Swift library `Foundation` is also imported because it's used by many features of the AWS SDK for Swift.

## Next steps
<a name="setup-nextsteps"></a>

Now that your tools and environment are ready for you to begin developing with AWS SDK for Swift, see [Getting started with the AWS SDK for Swift](getting-started.md), which demonstrates how to create and build a Swift project using AWS services.

# Authenticating with AWS using AWS SDK for Swift
<a name="authenticating"></a>

You must establish how your code authenticates with AWS when developing with AWS services. You can configure programmatic access to AWS resources in different ways depending on the environment and the AWS access available to you. For choices on all primary methods of authentication, and guidance on configuring it for the SDK, see [Authentication and access](https://docs.aws.amazon.com/sdkref/latest/guide/access.html) in the *AWS SDKs and Tools Reference Guide*. 

## Using console credentials
<a name="using-con-creds"></a>

 For local development, we recommend that new users use their existing AWS Management Console sign-in credentials for programmatic access to AWS services. After a browser-based authentication flow, AWS generates temporary credentials that work across local development tools like the AWS CLI, AWS Tools for PowerShell and AWS SDKs. This feature simplifies the process of configuring and managing AWS CLI credentials, especially if you prefer interactive authentication over managing long-term access keys. 

If you choose this method, follow the instructions to login with console credentials using the AWS CLI. See [Login for AWS local development using console credentials](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sign-in.html) for more details. 

 Once set up with AWS CLI, [the default credential provider chain](https://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/credential-providers.html#credproviders-default-credentials-provider-chain) will automatically start using the login token cached by AWS CLI to make requests. 

## Using IAM Identity Center
<a name="using-iam-id-cent"></a>

This method includes installing the AWS CLI for ease of configuration and for regularly signing in to the AWS access portal. 

 If you choose this method, complete the procedure for [IAM Identity Center authentication](https://docs.aws.amazon.com/sdkref/latest/guide/access-sso.html) in the *AWS SDKs and Tools Reference Guide*. Afterwards, your environment should contain the following elements:
+ The AWS CLI, which you use to start an AWS access portal session before you run your application.
+ A [shared AWS`config` file](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) having a `[default]` profile with a set of configuration values that can be referenced from the SDK. To find the location of this file, see [Location of the shared files](https://docs.aws.amazon.com/sdkref/latest/guide/file-location.html) in the *AWS SDKs and Tools Reference Guide*.
+  The shared `config` file sets the [https://docs.aws.amazon.com/sdkref/latest/guide/feature-region.html](https://docs.aws.amazon.com/sdkref/latest/guide/feature-region.html) setting. This sets the default AWS Region that the SDK uses for AWS requests. This Region is used for SDK service requests that aren't specified with a Region to use. 
+  The SDK uses the profile's [SSO token provider configuration](https://docs.aws.amazon.com/sdkref/latest/guide/feature-sso-credentials.html#feature-sso-credentials-profile) to acquire credentials before sending requests to AWS. The `sso_role_name` value, which is an IAM role connected to an IAM Identity Center permission set, allows access to the AWS services used in your application.

  The following sample `config` file shows a default profile set up with SSO token provider configuration. The profile's `sso_session` setting refers to the named [`sso-session` section](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html#section-session). The `sso-session` section contains settings to initiate an AWS access portal session.

  ```
  [default]
  sso_session = my-sso
  sso_account_id = 111122223333
  sso_role_name = SampleRole
  region = us-east-1
  output = json
  
  [sso-session my-sso]
  sso_region = us-east-1
  sso_start_url = https://provided-domain.awsapps.com/start
  sso_registration_scopes = sso:account:access
  ```

### Starting an AWS access portal session
<a name="accessportal"></a>

Before running an application that accesses AWS services, you need an active AWS access portal session for the SDK to use IAM Identity Center authentication to resolve credentials. Depending on your configured session lengths, your access will eventually expire and the SDK will encounter an authentication error. To sign in to the AWS access portal, run the following command in the AWS CLI.

```
$ aws sso login
```

If you followed the guidance and have a default profile setup, you do not need to call the command with a `--profile` option. If your SSO token provider configuration is using a named profile, the command is `aws sso login --profile named-profile`.

To optionally test if you already have an active session, you can run the following AWS CLI command.

```
$ aws sts get-caller-identity
```

If your session is active, the response to this command reports the IAM Identity Center account and permission set configured in the shared `config` file.

**Note**  
If you already have an active AWS access portal session and run `aws sso login`, you will not be required to provide credentials.   
The sign-in process might prompt you to allow the AWS CLI access to your data. Because the AWS CLI is built on top of the SDK for Python, permission messages might contain variations of the `botocore` name.

### More authentication information
<a name="credother"></a>

Human users, also known as *human identities*, are the people, administrators, developers, operators, and consumers of your applications. They must have an identity to access your AWS environments and applications. Human users that are members of your organization - that means you, the developer - are known as *workforce identities*. 

Use temporary credentials when accessing AWS. You can use an identity provider for your human users to provide federated access to AWS accounts by assuming roles, which provide temporary credentials. For centralized access management, we recommend that you use AWS IAM Identity Center (IAM Identity Center) to manage access to your accounts and permissions within those accounts. For more alternatives, see the following:
+ To learn more about best practices, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.
+ To create short-term AWS credentials, see [Temporary Security Credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) in the *IAM User Guide*.
+ To learn about other credential providers supported by teh AWS SDKs, see [Standardized credential providers](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html) in the *AWS SDKs and Tools Reference Guide*.

# Creating a simple application using the AWS SDK for Swift
<a name="simple-app"></a>

This chapter explores how to use the [Swift Package Manager](https://swift.org/package-manager/) — part of the standard Swift toolchain — to create and build a small project. The project uses the AWS SDK for Swift to output a list of available Amazon Simple Storage Service (Amazon S3) buckets.

## Creating a project using the AWS SDK for Swift
<a name="getting-started-intro"></a>

This chapter demonstrates how to create a small program that lists all the Amazon S3 buckets available on the default user account.

Goals for this project:
+ Create a project using Swift Package Manager.
+ Add the AWS SDK for Swift to the project.
+ Configure the project’s `Package.swift` file to describe the project and its dependencies.
+ Write code that uses Amazon S3 to get a list of the buckets on the default AWS account, then prints them to the screen.

Before we begin, make sure to prepare your development environment as described in [Set up](setting-up.md). To make sure you're set up properly, use the following command. This makes sure that Swift is available and which version it is.

```
$ swift --version
```

On macOS, you should see output that looks like the following (with possibly different version and build numbers):

```
swift-driver version: 1.87.1 Apple Swift version 5.9 (swiftlang-5.9.0.128.108 clang-1500.0.40.1)
Target: x86_64-apple-macosx14.0
```

On Linux, the output should look something like the following:

```
Swift version 5.9.0 (swift-5.9.0-RELEASE)
Target: x86_64-unknown-linux-gnu
```

If Swift is not installed, or is older than version 5.9, follow the instructions in [Setting up the AWS SDK for Swift](setting-up.md) to install or reinstall the tools.

**Get this example on GitHub**  
You can fork or download [this example](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/ListBuckets-Simple) from the [AWS SDK for Swift code examples](https://www.github.com/awsdocs/aws-doc-sdk-examples/) repository.

## Creating the project
<a name="getting-started-create"></a>

With the Swift tools installed, open a terminal session using your favorite terminal application (such as Terminal, iTerm, or the integrated terminal in your editor). 

At the terminal prompt, go to the directory where you want to create the project. Then, enter the following series of commands to create an empty Swift project for a standard executable program.

```
$ mkdir ListBuckets
$ cd ListBuckets
$ swift package init --type executable
$ mv Sources/main.swift Sources/entry.swift
```

This creates the directory for the examples project, moves into that directory, and initializes that directory with the Swift Package Manager (SwiftPM). The result is the basic file system structure for a simple executable program. The Swift source code file `main.swift` is also renamed to `entry.swift` to work around a bug in the Swift tools that involves the use of asynchronous code in the main function of a source file named `main.swift`.

```
ListBuckets/
├── Package.swift
└── Sources/
   └── entry.swift
```

Open your created project in your preferred text editor or IDE. On macOS, you can open the project in Xcode with the following:

```
$ xed .
```

As another example, you can open the project in Visual Studio Code with the following:

```
$ code .
```

## Configuring the package
<a name="getting-started-configure-package"></a>

After opening the project in your editor, open the `Package.swift` file. This is a Swift file that defines a SwiftPM [https://developer.apple.com/documentation/swift_packages/package](https://developer.apple.com/documentation/swift_packages/package) object that describes the project, its dependencies, and its build rules.

The first line of every `Package.swift` file must be a comment specifying the minimum version of the Swift toolchain needed to build the project. This isn't only informational. The version specified here can change the behavior of the tools for compatibility purposes. The AWS SDK for Swift requires at least version 5.9 of the Swift tools.

```
// swift-tools-version:5.9
```

### Specifying supported platforms
<a name="getting-started-configure-platforms"></a>

For projects whose target operating systems include any Apple platform, add or update the `[platforms](https://developer.apple.com/documentation/packagedescription/package/platforms)` property to include a list of the supported Apple platforms and minimum required versions. This list only specifies support for Apple platforms and doesn't preclude building for other platforms.

```
    // Let Xcode know the minimum Apple platforms supported.
    platforms: [
        .macOS(.v11),
        .iOS(.v13)
    ],
```

In this excerpt, the supported Apple platforms are macOS (version 11.0 and higher) and iOS/iPadOS (version 13 and higher).

### Setting up dependencies
<a name="getting-started-dependencies"></a>

The package dependency list needs to include the AWS SDK for Swift. This tells the Swift compiler to fetch the SDK and its dependencies before attempting to build the project.

```
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(
            url: "https://github.com/awslabs/aws-sdk-swift",
            from: "1.0.0"
        )
    ],
```

### Configuring the target
<a name="getting-started-targets"></a>

Now that the package depends on the AWS SDK for Swift, add a dependency to the executable program's target. Indicate that it relies on Amazon S3, which is offered by the SDK's `AWSS3` product.

```
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products from dependencies.
        .executableTarget(
            name: "ListBuckets-Simple",
            dependencies: [
                .product(name: "AWSS3", package: "aws-sdk-swift")
            ],
            path: "Sources")
    ]
```

## Accessing AWS services using Swift
<a name="using-services-from-swift-code"></a>

The example program's Swift code is found in the `Source/entry.swift` file. This file begins by importing the needed Swift modules, using the `import` statement.

```
import AWSClientRuntime
import AWSS3
import Foundation
```
+ `Foundation` is the standard Apple Foundation package.
+ `AWSS3` is the SDK module that's used to access Amazon S3.
+ `AWSClientRuntime` contains runtime components used by the SDK.

After you add the SDK for Swift to your project and import the service you want to use into your source code, you can create an instance of the client representing the service and use it to issue AWS service requests.

### Creating a service client object
<a name="create-a-client"></a>

Each AWS service is represented by a specific client class in the AWS SDK for Swift. For example, while the Amazon DynamoDB client class is called `[DynamoDBClient](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient)`, the class for Amazon Simple Storage Service is `S3Client`. To use Amazon S3 in this example, first create an `[S3Client](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client)` object on which to call the SDK's Amazon S3 functions.

```
        let configuration = try await S3Client.S3ClientConfiguration()
        //   configuration.region = "us-east-2" // Uncomment this to set the region programmatically.
        let client = S3Client(config: configuration)
```

### Issuing AWS service requests
<a name="issue-aws-requests"></a>

To issue a request to an AWS service, call the corresponding function on the service's client object. Each function's inputs are specified using a function-specific input structure as the value of the function's `input` parameter. For example, when calling `[S3Client.listBuckets(input:)](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/listbuckets(input:))`, `input` is a structure of type `[ListBucketsInput](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/listbucketsinput)`.

```
        // Use "Paginated" to get all the buckets.
        // This lets the SDK handle the 'continuationToken' in "ListBucketsOutput".
        let pages = client.listBucketsPaginated(
            input: input
        )
```

Functions defined by the AWS SDK for Swift run asynchronously, so the example uses `await` to block the program's execution until the result is available. If SDK functions encounter errors, they throw them so your code can handle them using a `do`-`catch` statement or by propagating them back to the caller.

### Getting all bucket names
<a name="get-bucket-names"></a>

This example's main program calls `getBucketNames()` to get an array containing all of the bucket names. That function is defined as follows.

```
// Return an array containing the names of all available buckets.
//
// - Returns: An array of strings listing the buckets.
func getBucketNames() async throws -> [String] {
    do {
        // Get an S3Client with which to access Amazon S3.
        let configuration = try await S3Client.S3ClientConfiguration()
        //   configuration.region = "us-east-2" // Uncomment this to set the region programmatically.
        let client = S3Client(config: configuration)

        // Use "Paginated" to get all the buckets.
        // This lets the SDK handle the 'continuationToken' in "ListBucketsOutput".
        let pages = client.listBucketsPaginated(
            input: ListBucketsInput( maxBuckets: 10)
        )

        // Get the bucket names.
        var bucketNames: [String] = []

        do {
            for try await page in pages {
                guard let buckets = page.buckets else {
                    print("Error: no buckets returned.")
                    continue
                }

                for bucket in buckets {
                    bucketNames.append(bucket.name ?? "<unknown>")
                }
            }

            return bucketNames
        } catch {
            print("ERROR: listBuckets:", dump(error))
            throw error
        }
    }
}
```

This function starts by creating an Amazon S3 client and calling its `[listBuckets(input:)](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/listbuckets(input:))` function to request a list of all of the available buckets. The list is returned asynchronously. After it's returned, the bucket list is fetched from the output structure's `buckets` property. If it's `nil`, an empty array is immediately returned to the caller. Otherwise, each bucket name is added to the array of bucket name strings, which is then returned to the caller.

## Adding the example entry point
<a name="getting-started-main-program"></a>

To allow the use of asynchronous functions from within `main()`, use Swift's `@main` attribute to create an object that contains a static `async` function called `main()`. Swift will use this as the program entry point.

```
@main
struct Main {
    static func main() async {
        do {
            let names = try await getBucketNames()

            print("Found \(names.count) buckets:")
            for name in names {
                print("  \(name)")
            }
        } catch let error as AWSServiceError {
            print("An Amazon S3 service error occurred: \(error.message ?? "No details available")")
        } catch {
            print("An unknown error occurred: \(dump(error))")
        }
    }
}
```

`main()` calls `getBucketNames()`, then outputs the returned list of names. Errors thrown by `getBucketNames()` are caught and handled. Errors of type `ServiceError`, which represent errors reported by the AWS service, are handled specially.

## Additional information
<a name="additional-information"></a>
+ [Setting up the AWS SDK for Swift](setting-up.md)
+ [Using the SDK for Swift](using.md)
+ [SDK for Swift code examples](swift_code_examples.md)