Set up Amplify GraphQL API
The Amplify API category provides an interface for retrieving and persisting your model data. The API category comes with default built-in support for AWS AppSync. The Amplify CLI allows you to define your API and provision a GraphQL service with CRUD operations and real-time functionality.
Goal
To setup and configure your application with Amplify API to save items in the backend.
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:
1amplify add api
Enter the following when prompted:
1? Please select from one of the below mentioned services:2 `GraphQL`3# The part below will show you some options you can change, if you wish to change any of them you can navigate with4# your arrow keys and update any field, otherwise you can click on `Continue` to move on5? Here is the GraphQL API that we will create. Select a setting to edit or continue6 `Continue`7? Choose a schema template:8 `Single object with fields (e.g., “Todo” with ID, name, description)`9? Do you want to edit the schema now?10 `No`
The guided schema creation will output amplify/backend/api/{api_name}/schema.graphql
containing the following:
1type Todo @model {2 id: ID!3 name: String!4 description: String5}
To push your changes to the cloud, execute the command:
1amplify push
Upon completion, amplifyconfiguration.json
will be updated to reference provisioned backend resources. Note that this file should already be a part of your project if you followed the Project setup walkthrough.
Generate Todo Model class
To generate the Todo
model, change directories to your project folder and execute the command:
1amplify codegen models
The generated files will be under the amplify/generated/models
directory. It is strongly advised not to put any hand written code in amplify/generated
directory as it gets re-generated each time codegen is run.
1AmplifyModels.swift2Todo.swift3Todo+Schema.swift
Drag and place the entire models
directory into Xcode to add them to your project.
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 and Amplify and click Add Package.
Initialize Amplify API
To initialize the Amplify API category, you are required to use the Amplify.add()
method for the plugin followed by calling Amplify.configure()
.
Add the following imports to the top of your AppDelegate.swift
file:
1import Amplify2import AWSAPIPlugin
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: AWSAPIPlugin(modelRegistration: AmplifyModels()))9 try Amplify.configure()10 print("Amplify configured with API plugin")11 } catch {12 print("Failed to initialize Amplify with \(error)")13 }14
15 return true16 }17}
Then in the App
scene, use UIApplicationDelegateAdaptor
property wrapper to use your custom AppDelegate
1@main2struct MyAmplifyApp: App {3 @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate4
5 var body: some Scene {6 WindowGroup {7 ContentView()8 }9 }10}
Upon building and running this application you should see the following in your console window:
1Amplify configured with API plugin
Create a Todo
1func createTodo() {2 let todo = Todo(name: "my first todo", description: "todo description")3 Amplify.API.mutate(request: .create(todo)) { event in4 switch event {5 case .success(let result):6 switch result {7 case .success(let todo):8 print("Successfully created the todo: \(todo)")9 case .failure(let graphQLError):10 print("Failed to create graphql \(graphQLError)")11 }12 case .failure(let apiError):13 print("Failed to create a todo", apiError)14 }15 }16}
Upon successfully executing this code, you should see an instance of todo
persisted in your dynamoDB table.
To navigate to your backend, run amplify console api
and choose GraphQL
. This will open the AppSync console to your GraphQL service. Select Data Sources
and select the Resource link in your TodoTable
to bring you to the DynamoDB Console. Select the items
tab to see the Todo
object that has been persisted in your database.
Next steps
Congratulations! You've created a Todo
object in your database. Check out the following links to see other Amplify API use cases: