Page updated Jan 16, 2024

Set up Amplify REST API

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 application with Amplify libraries integrated and a minimum target of any of the following:

  • iOS 13.0, using Xcode 14.1 or later.
  • macOS 10.15, using Xcode 14.1 or later.
  • tvOS 13.0, using Xcode 14.3 or later.
  • watchOS 9.0, using Xcode 14.3 or later.
  • visionOS 1.0, using Xcode 15 beta 2 or later. (Preview support - see below for more details.)

For a full example, please follow the project setup walkthrough.

visionOS support is currently in preview and can be used by targeting the visionos-preview branch. As new Xcode 15 beta versions are released, the branch will be updated with any necessary fixes on a best effort basis.

For more information on how to use the visionos-preview branch, see Platform Support.

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 Library for Swift 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.

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().

In your App scene, configure Amplify in the initializer:

1@main
2struct MyAmplifyApp: App {
3 var body: some Scene {
4 WindowGroup {
5 ContentView()
6 }
7 }
8
9 init() {
10 do {
11 try Amplify.add(plugin: AWSCognitoAuthPlugin())
12 try Amplify.add(plugin: AWSAPIPlugin())
13 try Amplify.configure()
14 print("Amplify configured with API and Auth plugin")
15 } catch {
16 print("Failed to initialize Amplify with \(error)")
17 }
18 }
19}

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

1import Amplify
2import AWSAPIPlugin

Add the following code to the 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() async {
2 let message = #"{"message": "my new Todo"}"#
3 let request = RESTRequest(path: "/todo", body: message.data(using: .utf8))
4 do {
5 let data = try await Amplify.API.post(request: request)
6 let str = String(decoding: data, as: UTF8.self)
7 print("Success: \(str)")
8 } catch let error as APIError {
9 print("Failed due to API error: ", error)
10 } catch {
11 print("Unexpected error: \(error)")
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.Publisher.create {
5 try await Amplify.API.post(request: request)
6 }
7 .sink {
8 if case let .failure(apiError) = $0 {
9 print("Failed", apiError)
10 }
11 }
12 receiveValue: { data in
13 let str = String(decoding: data, as: UTF8.self)
14 print("Success \(str)")
15 }
16 return sink
17}

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: