Page updated Jan 16, 2024

Set up Amplify REST API

Amplify iOS v1 is now in Maintenance Mode until May 31st, 2024. This means that we will continue to include updates to ensure compatibility with backend services and security. No new features will be introduced in v1.

Please use the latest version (v2) of Amplify Library for Swift to get started.

If you are currently using v1, follow these instructions to upgrade to v2.

Amplify libraries should be used for all new cloud connected applications. If you are currently using the AWS Mobile SDK for iOS, you can access the documentation here.

The Amplify API category provides an interface for making requests to your backend. The Amplify CLI deploys REST APIs and handlers using Amazon API Gateway and AWS Lambda.

Goal

To setup and configure your application with Amplify API to make requests to your API Gateway and trigger the lambda function using authorization provided by Amplify Auth.

Prerequisites

  • An iOS application targeting at least iOS 11.0 with Amplify libraries integrated

Configure API

To start provisioning api resources in the backend, go to your project directory and execute the command:

1amplify add api

Enter the following when prompted:

1? Please select from one of the below mentioned services:
2 `REST`
3? Provide a friendly name for your resource to be used as a label for this category in the project:
4 `api1f12345`
5? Provide a path (e.g., /book/{isbn}):
6 `/todo`
7? Choose a Lambda source
8 `Create a new Lambda function`
9? Provide a friendly name for your resource to be used as a label for this category in the project:
10 `restTodo123`
11? Provide the AWS Lambda function name:
12 `restTodoLambda123`
13? Choose the function runtime that you want to use:
14 `NodeJS`
15? Choose the function template that you want to use:
16 `Serverless ExpressJS function (Integration with API Gateway)`
17? Do you want to access other resources created in this project from your Lambda function?
18 `No`
19? Do you want to invoke this function on a recurring schedule?
20 `No`
21? Do you want to edit the local lambda function now? `No`
22Successfully added the Lambda function locally
23? Restrict API access
24 `Yes`
25? Who should have access?
26 `Authenticated and Guest users`
27? What kind of access do you want for Authenticated users?
28 `create, read, update, delete`
29? What kind of access do you want for Guest users?
30 `create, read, update, delete`
31Successfully added auth resource locally.
32? Do you want to add another path?
33 `No`

To push your changes to the cloud, execute the command:

1amplify push

Upon completion, amplifyconfiguration.json should be updated to reference provisioned backend storage resources. Note that these files should already be a part of your project if you followed the Project setup walkthrough.

Install Amplify Libraries

  1. To install Amplify Libraries in your application, open your project in Xcode and select File > Add Packages....

  2. Enter the Amplify iOS GitHub repo URL (https://github.com/aws-amplify/amplify-swift) into the search bar and click Add Package.

Note: Up to Next Major Version should be selected from the Dependency Rule dropdown.

  1. Lastly, choose AWSAPIPlugin, AWSCognitoAuthPlugin and Amplify. Then click Add Package.

To install the Amplify API and Authentication to your application, add both AmplifyPlugins/AWSAPIPlugin and AmplifyPlugins/AWSCognitoAuthPlugin to your Podfile. Your Podfile should look similar to:

1target 'MyAmplifyApp' do
2 use_frameworks!
3 pod 'Amplify'
4 pod 'AmplifyPlugins/AWSCognitoAuthPlugin'
5 pod 'AmplifyPlugins/AWSAPIPlugin'
6end

To install, download and resolve these pods, execute the command:

1pod install --repo-update

Now you can open your project by opening the .xcworkspace file using the following command:

1xed .

Initialize Amplify API

To initialize the Amplify API and Authentication categories, you are required to use the Amplify.addPlugin() method for each category you want. When you are done calling addPlugin() on each category, you finish configuring Amplify by calling Amplify.configure().

Add the following imports to the top of your AppDelegate.swift file:

1import Amplify
2import AWSAPIPlugin
1import Amplify
2import AmplifyPlugins

Add the following code

Create a custom AppDelegate, and add to your application:didFinishLaunchingWithOptions method

1class AppDelegate: NSObject, UIApplicationDelegate {
2 func application(
3 _ application: UIApplication,
4 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
5 ) -> Bool {
6
7 do {
8 try Amplify.add(plugin: AWSCognitoAuthPlugin())
9 try Amplify.add(plugin: AWSAPIPlugin())
10 try Amplify.configure()
11 print("Amplify configured with API and Auth plugin")
12 } catch {
13 print("Failed to initialize Amplify with \(error)")
14 }
15
16 return true
17 }
18}

Then in the App scene, use UIApplicationDelegateAdaptor property wrapper to use your custom AppDelegate

1@main
2struct MyAmplifyApp: App {
3 @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
4
5 var body: some Scene {
6 WindowGroup {
7 ContentView()
8 }
9 }
10}

Add to your AppDelegate's application:didFinishLaunchingWithOptions method

1func application(
2 _ application: UIApplication,
3 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
4) -> Bool {
5
6 do {
7 try Amplify.add(plugin: AWSCognitoAuthPlugin())
8 try Amplify.add(plugin: AWSAPIPlugin())
9 try Amplify.configure()
10 print("Amplify configured with API and Auth plugin")
11 } catch {
12 print("Failed to initialize Amplify with \(error)")
13 }
14
15 return true
16}

Upon building and running this application you should see the following in your console window:

1Amplify configured with API and Auth plugin

Make a POST Request

Send a POST request with a JSON body.

1func postTodo() {
2 let message = #"{"message": "my new Todo"}"#
3 let request = RESTRequest(path: "/todo", body: message.data(using: .utf8))
4 Amplify.API.post(request: request) { result in
5 switch result {
6 case .success(let data):
7 let str = String(decoding: data, as: UTF8.self)
8 print("Success \(str)")
9 case .failure(let apiError):
10 print("Failed", apiError)
11 }
12 }
13}
1func postTodo() -> AnyCancellable {
2 let message = #"{"message": "my new Todo"}"#
3 let request = RESTRequest(path: "/todo", body: message.data(using: .utf8))
4 let sink = Amplify.API.post(request: request)
5 .resultPublisher
6 .sink {
7 if case let .failure(apiError) = $0 {
8 print("Failed", apiError)
9 }
10 }
11 receiveValue: { data in
12 let str = String(decoding: data, as: UTF8.self)
13 print("Success \(str)")
14 }
15 return sink
16}

To navigate to your backend, go to the API Gateway console and select the API. The name of the API corresponds to the friendly name of the resource to be used as a label you specified earlier in the CLI steps.

Next steps

Congratulations! You've made a call to your API Gateway and triggered your Lambda function. Check out the following links to see other Amplify API use cases:

;