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 iOS application targeting at least iOS 11.0 with Amplify libraries integrated
- For a full example of 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 iOS 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.
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:
target 'MyAmplifyApp' do use_frameworks! pod 'Amplify' pod 'AmplifyPlugins/AWSCognitoAuthPlugin' pod 'AmplifyPlugins/AWSAPIPlugin'end
To install, download and resolve these pods, execute the command:
pod install --repo-update
Now you can open your project by opening the .xcworkspace
file using the following command:
xed .
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:
import Amplifyimport AWSAPIPlugin
import Amplifyimport AmplifyPlugins
Add the following code
Create a custom AppDelegate
, and add to your application:didFinishLaunchingWithOptions
method
class AppDelegate: NSObject, UIApplicationDelegate { 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 }}
Then in the App
scene, use UIApplicationDelegateAdaptor
property wrapper to use your custom AppDelegate
@mainstruct MyAmplifyApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene { WindowGroup { ContentView() } }}
Add to your AppDelegate's 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() { let message = #"{"message": "my new Todo"}"# let request = RESTRequest(path: "/todo", body: message.data(using: .utf8)) Amplify.API.post(request: request) { result in switch result { case .success(let data): let str = String(decoding: data, as: UTF8.self) print("Success \(str)") case .failure(let apiError): print("Failed", apiError) } }}
func postTodo() -> AnyCancellable { let message = #"{"message": "my new Todo"}"# let request = RESTRequest(path: "/todo", body: message.data(using: .utf8)) let sink = Amplify.API.post(request: request) .resultPublisher .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: