GraphQL API

You are currently viewing the AWS SDK for Mobile documentation which is a collection of low-level libraries. Use the Amplify libraries for all new app development. Learn more

You can view the Mobile SDK API reference here.

AWS AppSync helps you build data-driven apps with real-time and offline capabilities. The AppSync iOS SDK enables you to integrate your app with the AWS AppSync service and is based off of the Apollo project found here. The SDK supports multiple authorization models, handles subscription handshake protocols for real-time updates to data, and has built-in capabilities for offline support that makes it easy to integrate into your app.

You can integrate with AWS AppSync using the following steps:

  1. Setup the API endpoint and authentication information in the client side configuration.
  2. Generate Swift code from the API schema.
  3. Write app code to run queries, mutations and subscriptions.

The Amplify CLI provides support for AppSync that make this process easy. Using the CLI, you can configure an AWS AppSync API, download required client side configuration files, and generate client side code within minutes by running a few simple commands on the command line.

Configuration

The AWS SDKs support configuration through a centralized file called awsconfiguration.json that defines your AWS regions and service endpoints. You obtain this file in one of two ways, depending on whether you are creating your AppSync API in the AppSync console or using the Amplify CLI.

  • If you are creating your API in the console, navigate to the Getting Started page, and follow the steps in the Integrate with your app section. The awsconfiguration.json file you download is already populated for your specific API. Place the file in the root directory of your iOS project, and add it to your Xcode project.

  • If you are creating your API with the Amplify CLI (using amplify add api), the awsconfiguration.json file is automatically downloaded and updated each time you run amplify push to update your cloud resources. The file is placed in the root directory of your iOS project, and you need to add it to your Xcode project.

Code Generation

To execute GraphQL operations in iOS you need to run a code generation process, which requires both the GraphQL schema and the statements (for example, queries, mutations, or subscriptions) that your client defines. The Amplify CLI toolchain helps you do this by automatically pulling down your schema and generating default GraphQL queries, mutations, and subscriptions before kicking off the code generation process. If your client requirements change, you can alter these GraphQL statements and regenerate your types.

AppSync APIs Created in the Console

After installing the Amplify CLI open a terminal, go to your Xcode project root, and then run the following:

1amplify init
2amplify add codegen --apiId XXXXXX

The XXXXXX is the unique AppSync API identifier that you can find in the console in the root of your API's integration page. When you run this command you can accept the defaults, which create an API.swift file, and a graphql folder with your statements, in your root directory.

AppSync APIs Created Using the CLI

Navigate in your terminal to an Xcode project directory and run the following:

1amplify init ## Select iOS as your platform
2amplify add api ## Select GraphQL, API key, "Single object with fields Todo application"

Select GraphQL when prompted for service type:

1? Please select from one of the below mentioned services (Use arrow keys)
2❯ GraphQL
3 REST

The add api flow above will ask you some questions, such as if you already have an annotated GraphQL schema. If this is your first time using the CLI select No and let it guide you through the default project "Single object with fields (e.g., “Todo” with ID, name, description)" as it will be used in the code examples below. Later on, you can always change it.

Name your GraphQL endpoint and select authorization type:

1? Please select from one of the below mentioned services GraphQL
2? Provide API name: myTodosApi
3? Choose an authorization type for the API (Use arrow keys)
4❯ API key
5 Amazon Cognito User Pool

AWS AppSync API keys expire seven days after creation, and using API KEY authentication is only suggested for development. To change AWS AppSync authorization type after the initial configuration, use the $ amplify update api command and select GraphQL.

When you update your backend with push command, you can go to AWS AppSync Console and see that a new API is added under APIs menu item:

1amplify push

The amplify push process will prompt you to enter the codegen process and walk through configuration options. Accept the defaults and it will create a file named API.swift in your root directory (unless you choose to name it differently) as well as a directory called graphql with your documents. You also will have an awsconfiguration.json file that the AppSync client will use for initialization. At any time you can open the AWS console for your new API directly by running the following command:

1amplify console api

When prompted, select GraphQL. This will open the AWS AppSync console for you to run Queries, Mutations, or Subscriptions at the server and see the changes in your client app.

Import SDK and Config

To use AppSync in your Xcode project, modify your Podfile with a dependency of the AWS AppSync SDK as follows:

1target 'PostsApp' do
2 use_frameworks!
3 pod 'AWSAppSync'
4end

Run pod install from your terminal and open up the .xcworkspace Xcode project. Add the API.swift and awsconfiguration.json files to your project (File->Add Files to ..->Add) and then build your project, ensuring there are no issues.

Client Initialization

Initialize the AppSync client your application delegate by creating AWSAppSyncClientConfiguration and AWSAppSyncClient like the following:

1import AWSAppSync
2
3@UIApplicationMain
4class AppDelegate: UIResponder, UIApplicationDelegate {
5
6var appSyncClient: AWSAppSyncClient?
7
8func application(
9 _ application: UIApplication,
10 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
11) -> Bool {
12 do {
13 // You can choose the directory in which AppSync stores its persistent cache databases
14 let cacheConfiguration = try AWSAppSyncCacheConfiguration()
15
16 // AppSync configuration & client initialization
17 let appSyncServiceConfig = try AWSAppSyncServiceConfig()
18 let appSyncConfig = try AWSAppSyncClientConfiguration(appSyncServiceConfig: appSyncServiceConfig,
19 cacheConfiguration: cacheConfiguration)
20 appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
21 // Set id as the cache key for objects. See architecture section for details
22 appSyncClient?.apolloClient?.cacheKeyForObject = { $0["id"] }
23 } catch {
24 print("Error initializing appsync client. \(error)")
25 }
26 // other methods
27 return true
28}

AWSAppSyncServiceConfig represents the configuration information present in your awsconfiguration.json file.

Next, in your application code, you reference this in an appropriate lifecycle method such as viewDidLoad() if you are using UIKit:

1import AWSAppSync
2
3class Todos: UIViewController{
4 //Reference AppSync client
5 var appSyncClient: AWSAppSyncClient?
6
7 override func viewDidLoad() {
8 super.viewDidLoad()
9 //Reference AppSync client from App Delegate
10 let appDelegate = UIApplication.shared.delegate as! AppDelegate
11 appSyncClient = appDelegate.appSyncClient
12 }
13}

If you are using SwiftUI, you can add a reference to the shared AppSync client as @State to your View, and assign it in your view's initializer:

1// Remember to import AWSAppSync
2import AWSAppSync
3
4struct ContentView: View {
5
6 //Add an init method
7 @State var appSyncClient: AWSAppSyncClient?
8
9 init() {
10 let appDelegate = UIApplication.shared.delegate as! AppDelegate
11 appSyncClient = appDelegate.appSyncClient
12 }
13}

Run a Query

Now that the client is set up, you can run a GraphQL query. The syntax is appSyncClient?.fetch(query: <NAME>Query() {(result, error)}) where <NAME> comes from the GraphQL statements that amplify codegen created. For example, if you have a ListTodos query your code will look like the following:

1//Run a query
2appSyncClient?.fetch(query: ListTodosQuery()) { (result, error) in
3 if error != nil {
4 print(error?.localizedDescription ?? "")
5 return
6 }
7 result?.data?.listTodos?.items!.forEach { print(($0?.name)! + " " + ($0?.description)!) }
8}

Optionally, you can set a cache policy on the query as follows:

1appSyncClient?.fetch(query: ListTodosQuery(), cachePolicy: .returnCacheDataAndFetch) { (result, error) in

returnCacheDataAndFetch pulls results from the local cache first before retrieving data over the network. This gives a snappy UX and offline support.

Considerations for SwiftUI

When using List and ForEach for SwiftUI the structure needs to conform to Identifiable. The code generated for Swift does not make the structure Identifiable but as long as you have a unique id associated with the object then you can retroactively mark a field as unique. Here is some example code for ListTodosQuery()

1ForEach(listTodosStore.listTodos.identified(by:\.id)){ todo in
2 TodoCell(todoDetail: todo)
3}

Run a Mutation

To add data you need to run a GraphQL mutation. The syntax is appSyncClient?.perform(mutation: <NAME>Mutation() {(result, error)}) where <NAME> comes from the GraphQL statements that amplify codegen created. However, most GraphQL schemas organize mutations with an input type for maintainability, which is what the AppSync console and Amplify CLI do as well. Therefore, you need to pass this as a parameter called input, as in the following example:

1let mutationInput = CreateTodoInput(name: "Use AppSync", description:"Realtime and Offline")
2
3appSyncClient?.perform(mutation: CreateTodoMutation(input: mutationInput)) { (result, error) in
4 if let error = error as? AWSAppSyncClientError {
5 print("Error occurred: \(error.localizedDescription )")
6 }
7 if let resultError = result?.errors {
8 print("Error saving the item on server: \(resultError)")
9 return
10 }
11}

Working with Complex Objects

Sometimes you might want to create logical objects that have more complex data, such as images or videos, as part of their structure. For example, you might create a Person type with a profile picture or a Post type that has an associated image. You can use AWS AppSync to model these as GraphQL types and automatically store them to S3.

Subscribe to Data

Finally, it's time to set up a subscription to real-time data. The syntax appSyncClient?.subscribe(subscription: <NAME>Subscription() {(result, transaction, error)}) where <NAME> comes from the GraphQL statements that amplify codegen created. Note that the AppSync console and Amplify GraphQL transformer have a common nomenclature that puts the word On in front of a subscription as in the following example:

1// Set a variable to hold the subscription. E.g., this can be an instance variable on your view controller, or
2// a member variable in your AppSync setup code. Once you release this watcher, the subscription may be cancelled,
3// and your `resultHandler` will no longer be updated. If you wish to explicitly cancel the subscription, you can
4// invoke `subscriptionWatcher.cancel()`
5var subscriptionWatcher: Cancellable?
6
7// In your app code
8do {
9 subscriptionWatcher = try appSyncClient?.subscribe(
10 subscription: OnCreateTodoSubscription()
11 ) { result, transaction, error in
12 if let onCreateTodo = result?.data?.onCreateTodo, {
13 print(onCreateTodo.name + " " + onCreateTodo.description)
14 } else if let error = error {
15 print(error.localizedDescription)
16 }
17 }
18} catch {
19 print("Error starting subscription: \(error.localizedDescription)")
20}

Like mutations, subscriptions can also take input types, in which case they will be subscribing to particular events based on the input. To learn more about subscription arguments, see AWS AppSync Subscription Arguments.

Client Architecture

The AppSync client supports offline scenarios with a programming model that provides a "write through cache". This allows you to both render data in the UI when offline as well as add/update through an "optimistic response". The below diagram shows how the AppSync client interfaces with the network GraphQL calls, its offline mutation queue, the Apollo cache, and your application code.

Image

Your application code will interact with the AppSync client to perform GraphQL queries, mutations, or subscriptions. The AppSync client automatically performs the correct authorization methods when interfacing with the HTTP layer adding API Keys, tokens, or signing requests depending on how you have configured your setup. When you do a mutation, such as adding a new item (like a blog post) in your app the AppSync client adds this to a local queue (persisted to disk with SQLite) when the app is offline. When network connectivity is restored the mutations are sent to AppSync in serial allowing you to process the responses one by one.

Any data returned by a query is automatically written to the Apollo Cache (e.g. “Store”) that is persisted to disk via SQLite. The cache is structured as a key value store using a reference structure. There is a base “Root Query” where each subsequent query resides and then references their individual item results. You specify the reference key (normally “id”) in your application code. An example of the cache that has stored results from a “listPosts” query and “getPost(id:1)” query is below.

KeyValue
ROOT_QUERY[ROOT_QUERY.listPosts, ROOT_QUERY.getPost(id:1)]
ROOT_QUERY.listPosts{0, 1, ...,N}
Post:0{author:"Nadia", content:"ABC"}
Post:1{author:"Shaggy", content:"DEF"}
......
Post:N{author:"Pancho", content:"XYZ"}
ROOT_QUERY.getPost(id:1)ref: $Post:1

Notice that the cache keys are normalized where the getPost(id:1) query references the same element that is part of the listPosts query. This only happens when you define a common cache key to uniquely identify the objects. This is done when you configure the AppSync client in your AppDelegate with:

1//Use something other than "id" if your GraphQL type is different
2appSyncClient?.apolloClient?.cacheKeyForObject = { $0["id"] }

If you are performing a mutation, you can write an “optimistic response” anytime to this cache even if you are offline. You use the AppSync client to connect by passing in the query to update, reading the items off the cache. This normally returns a single item or list of items, depending on the GraphQL response type of the query to update. At this point you would add to the list, remove, or update it as appropriate and write back the response to the store persisting it to disk. When you reconnect to the network any responses from the service will overwrite the changes as the authoritative response.

Offline Mutations

As outlined in the architecture section, all query results are automatically persisted to disc with the AppSync client. For updating data through mutations when offline you will need to use an "optimistic response" with a transaction. This is done by passing an optimisticUpdate in the appSyncClient?.perform() mutation method using a transaction, where you pass in a query that will be updated in the cache. Inside of this transaction, you can write to the store via appSyncClient?.store?.withinReadWriteTransaction.

For example, the below code shows how you would update the CreateTodoMutation mutation from earlier by adding a optimisticUpdate: { (transaction) in do {...} catch {...} argument with a closure. This adds an item to the cache with transaction?.update() using a locally generated unique identifier. This might be enough for your app, however if the AppSync response returns a different value for ID (which many times is the case as best practice is generation of IDs at the service layer) then you will need to replace the value locally when a response is received. This can be done in the resultHandler by using appSyncClient?.store?.withinReadWriteTransaction() and transaction?.update() again.

1func optimisticCreateTodo(input: CreateTodoInput, query:ListTodosQuery) {
2 let createTodoInput = CreateTodoInput(name: input.name, description: input.description)
3 let createTodoMutation = CreateTodoMutation(input: createTodoInput)
4 let UUID = NSUUID().uuidString
5
6 self.appSyncClient?.perform(mutation: createTodoMutation, optimisticUpdate: { (transaction) in
7 do {
8 try transaction?.update(query: query) { (data: inout ListTodosQuery.Data) in
9 var listTodos = data.listTodos ?? ListTodosQuery.Data.ListTodo(items: [])
10 var items = listTodos.items ?? []
11
12 items.append(ListTodosQuery.Data.ListTodo.Item.init(
13 id: UUID,
14 name: input.name,
15 description: input.description!,
16 createdAt: "",
17 updatedAt: "")
18 )
19 listTodos.items = items
20 data.listTodos = listTodos
21 }
22 } catch {
23 print("Error updating cache with optimistic response for \(createTodoInput)")
24 }
25 }, resultHandler: { (result, error) in
26 if let result = result {
27 print("Added Todo Response from service: \(String(describing: result.data?.createTodo?.name))")
28 //Now remove the outdated entry in cache from optimistic write
29 let _ = self.appSyncClient?.store?.withinReadWriteTransaction { transaction in
30 try transaction.update(query: ListTodosQuery()) { (data: inout ListTodosQuery.Data) in
31 var pos = -1, counter = 0
32 for item in (data.listTodos?.items!)! {
33 if item?.id == UUID {
34 pos = counter
35 continue
36 }
37 counter += 1
38 }
39
40 if pos != -1 {
41 data.listTodos?.items?.remove(at: pos)
42 }
43 }
44 }
45 } else if let error = error {
46 print("Error adding Todo: \(error.localizedDescription)")
47 }
48 })
49}

You might add similar code in your app for updating or deleting items using an optimistic response, it would look largely similar except that you might overwrite or remove an element from the data.listTodos?.items array.

Authorization Modes

For client authorization AppSync supports API Keys, Amazon IAM credentials (we recommend using Amazon Cognito Identity Pools for this option), Amazon Cognito User Pools, and 3rd party OIDC providers. This is inferred from the awsconfiguration.json file when you call AWSAppSyncClientConfiguration(appSyncServiceConfig: AWSAppSyncServiceConfig().

API Key

API Key is the easiest way to setup and prototype your application with AppSync. It's also a good option if your application is completely public. If your application needs to interact with other AWS services besides AppSync, such as S3, you will need to use IAM credentials provided by Cognito Identity Pools, which also supports "Guest" access. See the authentication section for more details. For manual configuration, add the following snippet to your awsconfiguration.json file:

1{
2 "AppSync": {
3 "Default": {
4 "ApiUrl": "YOUR-GRAPHQL-ENDPOINT",
5 "Region": "us-east-1",
6 "ApiKey": "YOUR-API-KEY",
7 "AuthMode": "API_KEY"
8 }
9 }
10}

Add the following code to your app:

1do {
2 // Initialize the AWS AppSync configuration
3 let appSyncConfig = try AWSAppSyncClientConfiguration(
4 appSyncServiceConfig: AWSAppSyncServiceConfig(),
5 cacheConfiguration: AWSAppSyncCacheConfiguration()
6 )
7
8 // Initialize the AWS AppSync client
9 appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
10} catch {
11 print("Error initializing appsync client. \(error)")
12}

Cognito User Pools

Amazon Cognito User Pools is the most common service to use with AppSync when adding user Sign-Up and Sign-In to your application. If your application needs to interact with other AWS services besides AppSync, such as S3, you will need to use IAM credentials with Cognito Identity Pools. The Amplify CLI can automatically configure this for you when running amplify add auth and can also automatically federate User Pools with Identity Pools. This allows you to have both User Pool credentials for AppSync and AWS credentials for S3. You can then use the AWSMobileClient for automatic credentials refresh as outlined in the authentication section. For manual configuration, add the following snippet to your awsconfiguration.json file:

1{
2 "CognitoUserPool": {
3 "Default": {
4 "PoolId": "POOL-ID",
5 "AppClientId": "APP-CLIENT-ID",
6 "Region": "us-east-1"
7 }
8 },
9 "AppSync": {
10 "Default": {
11 "ApiUrl": "YOUR-GRAPHQL-ENDPOINT",
12 "Region": "us-east-1",
13 "AuthMode": "AMAZON_COGNITO_USER_POOLS"
14 }
15 }
16}

Add the following code to your app:

1class MyCognitoUserPoolsAuthProvider : AWSCognitoUserPoolsAuthProviderAsync {
2 func getLatestAuthToken(_ callback: @escaping (String?, Error?) -> Void) {
3 AWSMobileClient.default().getTokens { (tokens, error) in
4 if error != nil {
5 callback(nil, error)
6 } else {
7 callback(tokens?.idToken?.tokenString, nil)
8 }
9 }
10 }
11 }
12
13 func initializeAppSync() {
14 do {
15 // You can choose the directory in which AppSync stores its persistent cache databases
16 let cacheConfiguration = try AWSAppSyncCacheConfiguration()
17
18 // Initialize the AWS AppSync configuration
19 let appSyncConfig = try AWSAppSyncClientConfiguration(
20 appSyncServiceConfig: AWSAppSyncServiceConfig(),
21 userPoolsAuthProvider: MyCognitoUserPoolsAuthProvider(),
22 cacheConfiguration: cacheConfiguration
23 )
24
25 // Initialize the AWS AppSync client
26 appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
27 } catch {
28 print("Error initializing appsync client. \(error)")
29 }
30 }
31}

IAM

When using AWS IAM in a mobile application you should leverage Amazon Cognito Identity Pools. The Amplify CLI can automatically configure this for you when running amplify add auth. You can then use the AWSMobileClient for automatic credentials refresh as outlined in the authentication section For manual configuration, add the following snippet to your awsconfiguration.json file:

1{
2 "CredentialsProvider": {
3 "CognitoIdentity": {
4 "Default": {
5 "PoolId": "YOUR-COGNITO-IDENTITY-POOLID",
6 "Region": "us-east-1"
7 }
8 }
9 },
10 "AppSync": {
11 "Default": {
12 "ApiUrl": "YOUR-GRAPHQL-ENDPOINT",
13 "Region": "us-east-1",
14 "AuthMode": "AWS_IAM"
15 }
16 }
17}

Add the following code to your app:

1do {
2 // Initialize the AWS AppSync configuration
3 let appSyncConfig = try AWSAppSyncClientConfiguration(
4 appSyncServiceConfig: AWSAppSyncServiceConfig(),
5 credentialsProvider: AWSMobileClient.default(),
6 cacheConfiguration: AWSAppSyncCacheConfiguration()
7 )
8
9 // Initialize the AWS AppSync client
10 appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
11} catch {
12 print("Error initializing appsync client. \(error)")
13}

OIDC

If you are using a 3rd party OIDC provider you will need to configure it and manage the details of token refreshes yourself. Update the awsconfiguration.json file and code snippet as follows:

1{
2 "AppSync": {
3 "Default": {
4 "ApiUrl": "YOUR-GRAPHQL-ENDPOINT",
5 "Region": "us-east-1",
6 "AuthMode": "OPENID_CONNECT"
7 }
8 }
9}

Add the following code to your app:

1class MyOidcProvider: AWSOIDCAuthProvider {
2 func getLatestAuthToken() -> String {
3 // Fetch the JWT token string from OIDC Identity provider
4 // after the user is successfully signed-in
5 return "token"
6 }
7}
8
9do {
10 // Initialize the AWS AppSync configuration
11 let appSyncConfig = try AWSAppSyncClientConfiguration(
12 appSyncServiceConfig: AWSAppSyncServiceConfig(),
13 oidcAuthProvider: MyOidcProvider(),
14 cacheConfiguration: AWSAppSyncCacheConfiguration()
15 )
16
17 appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)
18} catch {
19 print("Error initializing appsync client. \(error)")
20}

Multi-Auth

This section talks about the capability of AWS AppSync to configure multiple authorization modes for a single AWS AppSync endpoint and region. Follow the AWS AppSync Multi-Auth to configure multiple authorization modes for your AWS AppSync endpoint.

You can now configure a single GraphQL API to deliver private and public data. Private data requires authenticated access using authorization mechanisms such as IAM, Cognito User Pools, and OIDC. Public data does not require authenticated access and is delivered through authorization mechanisms such as API Keys. You can also configure a single GraphQL API to deliver private data using more than one authorization type. For example, you can configure your GraphQL API to authorize some schema fields using OIDC, while other schema fields through Cognito User Pools and/or IAM.

As discussed in the above linked documentation, certain fields may be protected by different authorization types. This can lead the same query, mutation, or subscription to have different responses based on the authorization sent with the request; Therefore, it is recommended to use different AWSAppSyncClient objects for each authorization type. Instantiation of multiple AWSAppSyncClient objects is enabled by passing true to the useClientDatabasePrefix flag. The awsconfiguration.json generated by the AWS AppSync console and Amplify CLI will add an entry called ClientDatabasePrefix in the "AppSync" section. This will be used to differentiate the databases used for operations such as queries, mutations, and subscriptions.

Important Note: If you are an existing customer of AWS AppSync SDK for Android, the useClientDatabasePrefix has a default value of false. If you choose to use multiple AWSAppSyncClient objects, turning on useClientDatabasePrefix will change the location of the databases used by the client. The databases will not be automatically moved. You are responsible for migrating any data within the databases that you wish to keep and deleting the old databases on the device.

The following snippets highlight the new values in the awsconfiguration.json and the client code configurations.

The friendly_name illustrated here is created from Amplify CLI prompt. There are 4 clients in this configuration that connect to the same API except that they use different AuthMode and ClientDatabasePrefix.

1{
2 "Version": "1.0",
3 "AppSync": {
4 "Default": {
5 "ApiUrl": "https://xyz.us-west-2.amazonaws.com/graphql",
6 "Region": "us-west-2",
7 "AuthMode": "API_KEY",
8 "ApiKey": "da2-xyz",
9 "ClientDatabasePrefix": "friendly_name_API_KEY"
10 },
11 "friendly_name_AWS_IAM": {
12 "ApiUrl": "https://xyz.us-west-2.amazonaws.com/graphql",
13 "Region": "us-west-2",
14 "AuthMode": "AWS_IAM",
15 "ClientDatabasePrefix": "friendly_name_AWS_IAM"
16 },
17 "friendly_name_AMAZON_COGNITO_USER_POOLS": {
18 "ApiUrl": "https://xyz.us-west-2.amazonaws.com/graphql",
19 "Region": "us-west-2",
20 "AuthMode": "AMAZON_COGNITO_USER_POOLS",
21 "ClientDatabasePrefix": "friendly_name_AMAZON_COGNITO_USER_POOLS"
22 },
23 "friendly_name_OPENID_CONNECT": {
24 "ApiUrl": "https://xyz.us-west-2.amazonaws.com/graphql",
25 "Region": "us-west-2",
26 "AuthMode": "OPENID_CONNECT",
27 "ClientDatabasePrefix": "friendly_name_OPENID_CONNECT"
28 }
29 }
30}

The useClientDatabasePrefix is added on the client builder which signals to the builder that the ClientDatabasePrefix should be used from the AWSConfiguration object (awsconfiguration.json).

1let serviceConfig = try AWSAppSyncServiceConfig()
2let cacheConfig = AWSAppSyncCacheConfiguration(
3 useClientDatabasePrefix: true,
4 appSyncServiceConfig: serviceConfig
5)
6
7let clientConfig = AWSAppSyncClientConfiguration(
8 appSyncServiceConfig: serviceConfig,
9 cacheConfiguration: cacheConfig
10)
11
12let client = AWSAppSyncClient(appSyncConfig: clientConfig)

The following code creates a client factory to retrieve the client based on the authorization mode: public (API_KEY) or private (AWS_IAM).

1public enum AppSyncClientMode {
2 case `public`
3 case `private`
4}
5
6public class ClientFactory {
7 static var clients: [AppSyncClientMode:AWSAppSyncClient] = [:]
8
9 class func getAppSyncClient(mode: AppSyncClientMode) -> AWSAppSyncClient? {
10 return clients[mode];
11 }
12
13 class func initClients() throws {
14 let serviceConfigAPIKey = try AWSAppSyncServiceConfig()
15 let cacheConfigAPIKey = try AWSAppSyncCacheConfiguration(
16 useClientDatabasePrefix: true,
17 appSyncServiceConfig: serviceConfigAPIKey
18 )
19
20 let clientConfigAPIKey = try AWSAppSyncClientConfiguration(
21 appSyncServiceConfig: serviceConfigAPIKey,
22 cacheConfiguration: cacheConfigAPIKey
23 )
24
25 clients[AppSyncClientMode.public] = try AWSAppSyncClient(appSyncConfig: clientConfigAPIKey)
26
27 let serviceConfigIAM = try AWSAppSyncServiceConfig(forKey: "friendly_name_AWS_IAM")
28 let cacheConfigIAM = try AWSAppSyncCacheConfiguration(
29 useClientDatabasePrefix: true,
30 appSyncServiceConfig: serviceConfigIAM
31 )
32 let clientConfigIAM = try AWSAppSyncClientConfiguration(
33 appSyncServiceConfig: serviceConfigIAM,
34 cacheConfiguration: cacheConfigIAM
35 )
36 clients[AppSyncClientMode.private] = try AWSAppSyncClient(appSyncConfig: clientConfigIAM)
37 }
38}

This is what the usage would look like.

1ClientFactory.getAppSyncClient(AppSyncClientMode.private)?
2 .fetch(query: ListPostsQuery()) { (result, error) in
3 if error != nil {
4 print(error?.localizedDescription ?? "")
5 return
6 }
7 self.postList = result?.data?.listPosts
8 }

The following example uses API_KEY as the default authorization mode and AWS_IAM as an additional authorization mode.

1type Post @aws_api_key
2 @aws_iam {
3 id: ID!
4 author: String!
5 title: String
6 content: String
7 url: String @aws_iam
8 ups: Int @aws_iam
9 downs: Int @aws_iam
10 version: Int!
11}
  1. Add a post (Mutation) through ClientFactory.getAppSyncClient(AppSyncClientMode.private) using AWS_IAM authorization mode.

  2. Query the post through ClientFactory.getAppSyncClient(AppSyncClientMode.private) using AWS_IAM authorization mode.

  3. Query the post through ClientFactory.getAppSyncClient(AppSyncClientMode.public) using API_KEY authorization mode.

1appSyncClient?.fetch(query: GetPostQuery()) { (result, error) in
2 if error != nil {
3 print(error?.localizedDescription ?? "")
4 return
5 }
6 var post = result?.data?.getPost?
7 post.id
8 post.author
9 post.title
10 post.content
11 post.version
12 post.url // Null - because it's not authorized
13 post.ups // Null - because it's not authorized
14 post.downs // Null - because it's not authorized
15
16 result?.errors![0].message.contains("Not Authorized to access url on type Post")
17}

Clear cache

Clears the data cached by the AWSAppSyncClient object on the local device.

1appSyncClient.clearCaches(); // clear the queries, mutations and delta sync cache.

Selectively clear caches ClearCacheOptions.

1// Selectively clear caches, omit parameters to keep those caches
2let clearCacheOptions = ClearCacheOptions(
3 clearQueries: true,
4 clearMutations: true,
5 clearSubscriptions: true
6)
7appSyncClient.clearCaches(options: clearCacheOptions)

Delta Sync

DeltaSync allows you to perform automatic synchronization with an AWS AppSync GraphQL server. The client will perform reconnection, exponential backoff, and retries when network errors take place for simplified data replication to devices. It does this by taking the results of a GraphQL query and caching it in the local Apollo cache.

In the most basic form, you can use a single query with the API to replicate the state from the backend to the client. This is referred to as a "Base Query" and could be a list operation for a GraphQL type which might correspond to a DynamoDB table. For large tables where the content changes frequently and devices switch between offline and online frequently as well, pulling all changes for every network reconnect can result in poor performance on the client. In these cases you can provide the client API a second query called the "Delta Query" which will be merged into the cache. When you do this the Base Query is run an initial time to hydrate the cache with data, and on each network reconnect the Delta Query is run to just get the changed data. The Base Query is also run on a regular basis as a "catch-up" mechanism. By default this is every 24 hours however you can make it more or less frequent.

By allowing clients to separate the base hydration of the cache using one query and incremental updates in another query, you can move the computation from your client application to the backend. This is substantially more efficient on the clients when regularly switching between online and offline states. This could be implemented in your AWS AppSync backend in different ways such as using a DynamoDB Query on an index along with a conditional expression. You can also leverage Pipeline Resolvers to partition your records to have the delta responses come from a second table acting as a journal. A full sample with CloudFormation is available in the AppSync documentation. The rest of this documentation will focus on the client usage.

You can also use Delta Sync functionality with GraphQL subscriptions, taking advantage of both only sending changes to the clients when they switch network connectivity but also when they are online. In this case you can pass a third query called the "Subscription Query" which is a standard GraphQL subscription statement. When the device is connected, these are processed as normal and the client API simply helps make setting up realtime data easy. However, when the device transitions from offline to online, to account for high velocity writes the client will execute the resubscription along with synchronization and message processing in the following order:

  1. Subscribe to any queries defined and store results in an incoming queue
  2. Run the appropriate query (If baseRefreshIntervalInSeconds has elapsed, run the Base Query otherwise only run the Delta Query)
  3. Update the cache with results from the appropriate query
  4. Drain the subscription queue and continue processing as normal

Finally, you might have other queries which you wish to represent in your application other than the base cache hydration. For instance a getItem(id:ID) or other specific query. If your alternative query corresponds to items which are already in the normalized cache, you can point them at these cache entries with the cacheUpdates function which returns an array of queries and their variables. The DeltaSync client will then iterate through the items and populate a query entry for each item on your behalf. If you wish to use additional queries which don't correspond to items in your base query cache, you can always create another instance of the appSyncClient?.sync() process.

Usage

1// instance variable in your view controller
2var deltaWatcher: Cancellable?
3
4// Start DeltaSync
5// Provides the ability to sync using a baseQuery, subscription, deltaQuery, and a refresh interval
6let allPostsBaseQuery = ListPostsQuery()
7let allPostsDeltaQuery = ListPostsDeltaQuery()
8let postsSubscription = OnDeltaPostSubscription()
9
10deltaWatcher = appSyncClient?.sync(
11 baseQuery: allPostsBaseQuery,
12 baseQueryResultHandler: { (result, error) in
13
14 },
15 subscription: postsSubscription,
16 subscriptionResultHandler: { (result, transaction, error) in
17
18 },
19 deltaQuery: allPostsDeltaQuery,
20 deltaQueryResultHandler: { (result, transaction, error) in
21
22 }
23)
24
25//Stop DeltaSync
26deltaWatcher.cancel()

The method parameters

  • baseQuery the base query to get the baseline state. (REQUIRED)
  • baseQueryResultHandler callback to handle the baseQuery results. (REQUIRED)
  • subscription subscription to get changes on the fly.
  • subscriptionResultHandler callback to handle the subscription messages.
  • deltaQuery the catch-up query
  • deltaQueryResultHandler callback to handle the deltaQuery results.
  • syncConfiguration time duration (specified in seconds) when the base query will be re-run to get an updated baseline state. Defaults to 24 hours.
  • returnValue returns a Cancellable object that can be used later to cancel the sync operation by calling the cancel() method.

Note that above only the baseQuery and baseQueryResultHandler are required parameters. You can call the API in different ways such as:

1//Performs sync only with base query
2appSyncClient?.sync(baseQuery: baseQuery, baseQueryResultHandler: baseQueryResultHandler)
3
4//Performs sync with delta but no subscriptions
5appSyncClient?.sync(
6 baseQuery: baseQuery,
7 baseQueryResultHandler: baseQueryResultHandler,
8 deltaQuery: deltaQuery,
9 deltaQueryResultHandler: deltaQueryResultHandler
10)

Example

The following section walks through the details of creating an app using Delta Sync. You will use a simple Posts App that has a view that displays a list of posts and keeps it synchronized using the Delta Sync functionality. You will use an array called postList to collect and manage the posts and a UIViewController to power the UI.

Create Sync Handler Function

Create a new method named loadPostsWithSyncFeature which will be called from the viewDidLoad() method of your view controller.

1class YourAppViewController: UIViewController {
2
3 var appSyncClient: AWSAppSyncClient?
4 var deltaWatcher: Cancellable?
5
6 @IBOutlet weak var tableView: UITableView!
7 var postList: [ListPostsQuery.Data.ListPost?]? = [] {
8 didSet {
9 tableView.reloadData()
10 }
11 }
12
13 override func viewDidLoad() {
14 super.viewDidLoad()
15
16 // Fetch AppSync client from AppDelegate or from the place where it was initialized.
17 let appDelegate = UIApplication.shared.delegate as! AppDelegate
18 appSyncClient = appDelegate.appSyncClient
19
20 // Set table view delegate
21 self.tableView.dataSource = self
22 self.tableView.delegate = self
23
24 // Call the new method which you just added.
25 loadPostsWithSyncFeature()
26 }
27
28 func loadPostsWithSyncFeature() {
29 // Sync operation will be added here.
30 }
31}

Create Helpers to Add/ Update/ Delete Posts in Cache

Helper function to load posts from cache:

1func loadAllPostsFromCache() {
2 appSyncClient?.fetch(
3 query: ListPostsQuery(),
4 cachePolicy: .returnCacheDataDontFetch
5 ) { (result, error) in
6 if error != nil {
7 print(error?.localizedDescription ?? "")
8 return
9 }
10 self.postList = result?.data?.listPosts
11 }
12}

Helper function to Add or Update a post:

1func addOrUpdatePostInQuery(id: GraphQLID, title: String, author: String, content: String) {
2 // Create a new object for the desired query, where the new object content should reside
3 let postToAdd = ListPostsQuery.Data.ListPost(
4 id: id,
5 author: author,
6 title: title,
7 content: content
8 )
9 print("App: Processing \(id) for add/ update")
10 let _ = appSyncClient?.store?.withinReadWriteTransaction({ (transaction) in
11 do {
12 // Update the local store with the newly received data
13 try transaction.update(query: ListPostsQuery()) { (data: inout ListPostsQuery.Data) in
14 guard let items = data.listPosts else {
15 return
16 }
17 var pos = -1
18 var counter = 0
19 for post in items {
20 if post?.id == id {
21 pos = counter
22 continue
23 }
24 counter += 1
25 }
26 // Post is not present in query, add it.
27 if pos == -1 {
28 print("App: Adding \(id) now.")
29 data.listPosts?.append(postToAdd)
30 } else {
31 // It was an update operation, post will be automatically updated in cache.
32 }
33 }
34 } catch {
35 print("App: Error updating store")
36 }
37 })
38 self.loadAllPostsFromCache()
39}

Helper function to Delete a post:

1func deletePostFromCache(uniqueId: GraphQLID) {
2 // Remove local object from cache.
3 print("App: Removing \(uniqueId) from cache.")
4 let _ = appSyncClient?.store?.withinReadWriteTransaction({ (transaction) in
5 do {
6 try transaction.update(query: ListPostsQuery(), { (data: inout ListPostsQuery.Data) in
7 guard let items = data.listPosts else {
8 return
9 }
10 var pos = -1
11 var counter = 0
12 for post in items {
13 if post?.id == uniqueId {
14 pos = counter
15 continue
16 }
17 counter += 1
18 }
19 print("App: \(uniqueId) index: \(pos).")
20 if pos != -1 {
21 print("App: Removing now \(uniqueId)")
22 data.listPosts?.remove(at: pos)
23 }
24 })
25 } catch {
26 print("App: Error updating store")
27 }
28 })
29 self.loadAllPostsFromCache()
30}

Implement the new sync function

Now, update the loadPostsWithSyncFeature function with the calls to your helper methods to make sure all changes are updated in the UI.

1func loadPostsWithSyncFeature() {
2 let allPostsBaseQuery = ListPostsQuery()
3 let allPostsDeltaQuery = ListPostsDeltaQuery()
4 let postsSubscription = OnDeltaPostSubscription()
5
6 deltaWatcher = appSyncClient?.sync(
7 baseQuery: allPostsBaseQuery,
8 baseQueryResultHandler: { (result, error) in
9 if error != nil {
10 print(error?.localizedDescription ?? "")
11 return
12 }
13 self.postList = result?.data?.listPosts
14 },
15 subscription: postsSubscription,
16 subscriptionResultHandler: { (result, transaction, error) in
17 if let result = result {
18 guard result.data != nil, result.data?.onDeltaPost != nil else {
19 return
20 }
21 // If the Post is to be deleted from the cache.
22 if(result.data?.onDeltaPost?.awsDs == DeltaAction.delete) {
23 self.deletePostFromCache(uniqueId: result.data!.onDeltaPost!.id)
24 return
25 }
26 // Store a reference to the new object
27 let newPost = result.data!.onDeltaPost!
28 self.addOrUpdatePostInQuery(
29 id: newPost.id,
30 title: newPost.title,
31 author: newPost.author,
32 content: newPost.content
33 )
34 } else if let error = error {
35 print(error.localizedDescription)
36 }
37 },
38 deltaQuery: allPostsDeltaQuery,
39 deltaQueryResultHandler: { (result, transaction, error) in
40 if let result = result {
41 guard result.data != nil, result.data?.listPostsDelta != nil else {
42 return
43 }
44 // Store a reference to the new updates
45 let deltas = result.data!.listPostsDelta!
46
47 for deltaPost in deltas {
48 print("App: Processing update on Post ID: \(deltaPost!.id)")
49 if deltaPost?.awsDs == DeltaAction.delete {
50 self.deletePostFromCache(uniqueId: deltaPost!.id)
51 continue
52 } else {
53 self.addOrUpdatePostInQuery(id: deltaPost!.id, title: deltaPost!.title, author: deltaPost!.author, content: deltaPost!.content)
54 }
55 }
56 } else if let error = error {
57 print(error.localizedDescription)
58 }
59 // Set a sync configuration of 5 minutes.
60 },
61 syncConfiguration: SyncConfiguration(baseRefreshIntervalInSeconds: 300)
62 )
63}

Once you have all of these pieces in place, you will tie it all together by invoking the Delta Sync functionality as follows.

Delta Sync Lifecycle

The delta sync process runs at various times, in response to different conditions.

  • Runs immediately, when you make the call to sync as shown above. This will be the initial run and it will first execute the base query from the cache, setup the subscription and execute the base or delta Query based on when it was last run. It will always run the base query if running for the first time.
  • Runs when the device that is running the app transitions from offline to online. Depending on the duration for which the device was offline, either the deltaQuery or the baseQuery will be run.
  • Runs when the app transitions from background to foreground. Once again, depending on how long the app was in the background, either the deltaQuery or the baseQuery will be run.
  • Runs once every time based on the time specified in sync configuration as part of a periodic catch-up.