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 or later. (Preview support - see below for more details.)
For a full example, please follow the project setup walkthrough.
Configure API
To start provisioning api resources in the backend, go to your project directory and execute the command:
amplify add api
Enter the following when prompted:
? Please select from one of the below mentioned services: `REST`? Provide a friendly name for your resource to be used as a label for this category in the project: `api1f12345`? Provide a path (e.g., /book/{isbn}): `/todo`? Choose a Lambda source `Create a new Lambda function`? Provide a friendly name for your resource to be used as a label for this category in the project: `restTodo123`? Provide the AWS Lambda function name: `restTodoLambda123`? Choose the function runtime that you want to use: `NodeJS`? Choose the function template that you want to use: `Serverless ExpressJS function (Integration with API Gateway)`? Do you want to access other resources created in this project from your Lambda function? `No`? Do you want to invoke this function on a recurring schedule? `No`? Do you want to edit the local lambda function now? `No`Successfully added the Lambda function locally? Restrict API access `Yes`? Who should have access? `Authenticated and Guest users`? What kind of access do you want for Authenticated users? `create, read, update, delete`? What kind of access do you want for Guest users? `create, read, update, delete`Successfully added auth resource locally.? Do you want to add another path? `No`
To push your changes to the cloud, execute the command:
amplify 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
-
To install Amplify Libraries in your application, open your project in Xcode and select File > Add Packages....
-
Enter the Amplify Library for Swift GitHub repo URL (
https://github.com/aws-amplify/amplify-swift
) into the search bar and click Add Package.
- 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:
@mainstruct MyAmplifyApp: App { var body: some Scene { WindowGroup { ContentView() } }
init() { do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.add(plugin: AWSAPIPlugin()) try Amplify.configure() print("Amplify configured with API and Auth plugin") } catch { print("Failed to initialize Amplify with \(error)") } }}
Add the following imports to the top of your AppDelegate.swift
file:
import Amplifyimport AWSAPIPlugin
Add the following code to the application:didFinishLaunchingWithOptions
method:
func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.add(plugin: AWSAPIPlugin()) try Amplify.configure() print("Amplify configured with API and Auth plugin") } catch { print("Failed to initialize Amplify with \(error)") }
return true}
Upon building and running this application you should see the following in your console window:
Amplify configured with API and Auth plugin
Make a POST Request
Send a POST request with a JSON body.
func postTodo() async { let message = #"{"message": "my new Todo"}"# let request = RESTRequest(path: "/todo", body: message.data(using: .utf8)) do { let data = try await Amplify.API.post(request: request) let str = String(decoding: data, as: UTF8.self) print("Success: \(str)") } catch let error as APIError { print("Failed due to API error: ", error) } catch { print("Unexpected error: \(error)") }}
func postTodo() -> AnyCancellable { let message = #"{"message": "my new Todo"}"# let request = RESTRequest(path: "/todo", body: message.data(using: .utf8)) let sink = Amplify.Publisher.create { try await Amplify.API.post(request: request) } .sink { if case let .failure(apiError) = $0 { print("Failed", apiError) } } receiveValue: { data in let str = String(decoding: data, as: UTF8.self) print("Success \(str)") } return sink}
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: