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:
amplify add apiEnter the following when prompted:
? Please select from one of the below mentioned services: `GraphQL`# The part below will show you some options you can change, if you wish to change any of them you can navigate with# your arrow keys and update any field, otherwise you can click on `Continue` to move on? Here is the GraphQL API that we will create. Select a setting to edit or continue `Continue`? Choose a schema template: `Single object with fields (e.g., “Todo” with ID, name, description)`? Do you want to edit the schema now? `No`The guided schema creation will output amplify/backend/api/{api_name}/schema.graphql containing the following:
type Todo @model { id: ID! name: String! description: String}To push your changes to the cloud, execute the command:
amplify pushUpon 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:
amplify codegen modelsThe 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.
AmplifyModels.swiftTodo.swiftTodo+Schema.swiftDrag 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.
To install the Amplify API to your application, add AmplifyPlugins/AWSAPIPlugin to your Podfile. Your Podfile should look similar to:
target 'MyAmplifyApp' do use_frameworks! pod 'Amplify' pod 'AmplifyPlugins/AWSAPIPlugin'endTo install, download and resolve these pods, execute the command:
pod install --repo-updateNow you can open your project by opening the .xcworkspace file using the following command:
xed .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:
import Amplifyimport AWSAPIPluginimport Amplifyimport AmplifyPluginsAdd 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: AWSAPIPlugin(modelRegistration: AmplifyModels())) try Amplify.configure() print("Amplify configured with API 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: AWSAPIPlugin(modelRegistration: AmplifyModels())) try Amplify.configure() print("Amplify configured with API 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 pluginCreate a Todo
func createTodo() { let todo = Todo(name: "my first todo", description: "todo description") Amplify.API.mutate(request: .create(todo)) { event in switch event { case .success(let result): switch result { case .success(let todo): print("Successfully created the todo: \(todo)") case .failure(let graphQLError): print("Failed to create graphql \(graphQLError)") } case .failure(let apiError): print("Failed to create a todo", apiError) } }}Make sure you have the additional import at the top of your file
import Combinefunc createTodo() -> AnyCancellable { let todo = Todo(name: "my first todo", description: "todo description") let sink = Amplify.API.mutate(request: .create(todo)) .resultPublisher .sink { completion in if case let .failure(error) = completion { print("Failed to create graphql \(error)") } } receiveValue: { result in switch result { case .success(let todo): print("Successfully created the todo: \(todo)") case .failure(let graphQLError): print("Could not decode result: \(graphQLError)") } } return sink}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: