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

AWS AppSync helps you build data-driven apps with real-time and offline capabilities. The AppSync Android 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 Java 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 ./app/src/main/res/raw directory of your Android Studio project for code generation.

  • 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 ./app/src/main/res/raw directory of your Android Studio project.

Code Generation

To execute GraphQL operations in Android 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 makes this easy for you by automatically pulling down your schema and generating default GraphQL queries, mutations, and subscriptions before kicking off the code generation process using Gradle. If your client requirements change, you can alter these GraphQL statements and kick off a Gradle build again to regenerate the types.

AppSync APIs Created in the Console

After installing the Amplify CLI open a terminal, go to your Android Studio 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 a ./src/main.graphql folder structure with your statements. When you add the required Gradle dependencies later, the generated packages are automatically added to your project.

Note: It is not necessary to run the command amplify codegen after adding an API, as code generation is done by the Gradle build process. However, if you subsequently update your API in the AppSync Console, you will need to re-run amplify codegen to update the local schema.json and .graphql with the modified schema.

AppSync APIs Created Using the CLI

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

1amplify init ## Select Android 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 ./src/main.graphql folder structure 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 Android studio project, modify the project's build.gradle by adding the Maven plugin repositories, and the AppSync Gradle plugin to dependencies.

1buildscript {
2 repositories {
3 maven {
4 url "https://plugins.gradle.org/m2/"
5 }
6 // ...
7 }
8
9 dependencies {
10 classpath 'com.amazonaws:aws-android-sdk-appsync-gradle-plugin:3.4.0'
11 // ...
12 }
13 // ...
14}
15
16allprojects {
17 repositories {
18 maven {
19 url "https://plugins.gradle.org/m2/"
20 }
21 // ...
22 }
23 // ...
24}

Next, in the build.gradle (Module :app) file, add in a plugin of apply plugin: 'com.amazonaws.appsync' and a dependency of implementation 'com.amazonaws:aws-android-sdk-appsync:3.4.0'. For example:

1plugins {
2 id 'com.android.application'
3 id 'com.amazonaws.appsync' // REQUIRED
4}
5android {
6 // Typical items
7}
8dependencies {
9 // REQUIRED: Typical dependencies
10 implementation 'com.amazonaws:aws-android-sdk-appsync:3.4.0'
11}

Finally, update your AndroidManifest.xml with updates to <uses-permissions> for network calls and offline state.

1<uses-permission android:name="android.permission.INTERNET"/>
2 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
3 <uses-permission android:name="android.permission.WAKE_LOCK" />
4 <uses-permission android:name="android.permission.READ_PHONE_STATE" />
5 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
6 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
7
8 <!--other code-->
9
10 <application
11 android:allowBackup="true"
12 android:icon="@mipmap/ic_launcher"
13 android:label="@string/app_name"
14 android:roundIcon="@mipmap/ic_launcher_round"
15 android:supportsRtl="true"
16 android:theme="@style/AppTheme">
17
18 <!--other code-->
19 </application>

Build your Project

Do not skip this step! Run gradlew build, or build your application via Android Studio. This will trigger the AppSync Gradle plugin that you added above to generate Java classes in your build folder based off of your schema files. These classes will be needed before proceeding to the steps below.

Client Initialization

Inside your application code, such as the onCreate() lifecycle method of your activity class, you can initialize the AppSync client using an instance of AWSConfiguration() in the AWSAppSyncClient builder like the following:

1private AWSAppSyncClient mAWSAppSyncClient;
2
3@Override
4protected void onCreate(Bundle savedInstanceState) {
5 super.onCreate(savedInstanceState);
6 setContentView(R.layout.activity_main);
7 mAWSAppSyncClient = AWSAppSyncClient.builder()
8 .context(getApplicationContext())
9 .awsConfiguration(new AWSConfiguration(getApplicationContext()))
10 // If you are using complex objects (S3) then uncomment
11 //.s3ObjectManager(new S3ObjectManagerImplementation(new AmazonS3Client(AWSMobileClient.getInstance())))
12 .build();
13}

AWSConfiguration() reads configuration information in the awsconfiguration.json file. By default, the information in the Default section of the json file is used.

Run a Query

Now that the client is configured, you can run a GraphQL query. The syntax of the callback is GraphQLCall.Callback<{NAME}Query.Data> where {NAME} comes from the GraphQL statements that amplify codegen created after you ran a Gradle build. You invoke this from an instance of the AppSync client with a similar syntax of .query({NAME}Query.builder().build()). For example, if you have a ListTodos query, your code will look like the following:

1public void query(){
2 mAWSAppSyncClient.query(ListTodosQuery.builder().build())
3 .responseFetcher(AppSyncResponseFetchers.CACHE_AND_NETWORK)
4 .enqueue(todosCallback);
5}
6
7private GraphQLCall.Callback<ListTodosQuery.Data> todosCallback = new GraphQLCall.Callback<ListTodosQuery.Data>() {
8 @Override
9 public void onResponse(@Nonnull Response<ListTodosQuery.Data> response) {
10 Log.i("Results", response.data().listTodos().items().toString());
11 }
12
13 @Override
14 public void onFailure(@Nonnull ApolloException e) {
15 Log.e("ERROR", e.toString());
16 }
17};

Optionally, you can change the cache policy on AppSyncResponseFetchers, but we recommend leaving CACHE_AND_NETWORK because it pulls results from the local cache first before retrieving data over the network. This gives a snappy UX and offline support.

Run a Mutation

To add data you need to run a GraphQL mutation. The syntax of the callback is GraphQLCall.Callback<{NAME}Mutation.Data> where {NAME} comes from the GraphQL statements that amplify codegen created after a Gradle build. However, most GraphQL schemas organize mutations with an input type for maintainability, which is what the Amplify CLI does as well. Therefore you'll pass this as a parameter called input created with a second builder. You invoke this from an instance of the AppSync client with a similar syntax of .mutate({NAME}Mutation.builder().input({Name}Input).build()) like the following:

1public void mutation(){
2 CreateTodoInput createTodoInput = CreateTodoInput.builder()
3 .name("Use AppSync")
4 .description("Realtime and Offline")
5 .build();
6
7 mAWSAppSyncClient.mutate(CreateTodoMutation.builder().input(createTodoInput).build())
8 .enqueue(mutationCallback);
9}
10
11private GraphQLCall.Callback<CreateTodoMutation.Data> mutationCallback = new GraphQLCall.Callback<CreateTodoMutation.Data>() {
12 @Override
13 public void onResponse(@Nonnull Response<CreateTodoMutation.Data> response) {
14 Log.i("Results", "Added Todo");
15 }
16
17 @Override
18 public void onFailure(@Nonnull ApolloException e) {
19 Log.e("Error", e.toString());
20 }
21};

Subscribe to Data

Finally, it's time to set up a subscription to real-time data. The callback is just AppSyncSubscriptionCall.Callback and you invoke it with a client .subscribe() call and pass in a builder with syntax of {NAME}Subscription.builder() where {NAME} comes from the GraphQL statements that amplify codegen and Gradle build 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:

1private AppSyncSubscriptionCall<OnCreateTodoSubscription.Data> subscriptionWatcher;
2
3private void subscribe() {
4 OnCreateTodoSubscription subscription = OnCreateTodoSubscription.builder().build();
5 subscriptionWatcher = mAWSAppSyncClient.subscribe(subscription);
6 subscriptionWatcher.execute(subCallback);
7}
8
9private AppSyncSubscriptionCall.Callback<OnCreateTodoSubscription.Data> subCallback = new AppSyncSubscriptionCall.Callback<OnCreateTodoSubscription.Data>() {
10 @Override
11 public void onResponse(@Nonnull Response<OnCreateTodoSubscription.Data> response) {
12 Log.i("Subscription", response.data().toString());
13 }
14
15 @Override
16 public void onFailure(@Nonnull ApolloException e) {
17 Log.e("Subscription", e.toString());
18 }
19
20 @Override
21 public void onCompleted() {
22 Log.i("Subscription", "Subscription completed");
23 }
24};

Subscriptions can also take input types like mutations, in which case they will be subscribing to particular events based on the input.

Background Tasks

All GraphQL operations in the Android client are automatically run as asynchronous tasks and can be safely called from any thread. If you have a need to run GraphQL operations from a background thread you can do it with a Runnable() like the example below:

1final CountDownLatch mCountDownLatch = new CountDownLatch(1);
2
3new Thread(new Runnable() {
4 @Override
5 public void run() {
6 Looper.prepare();
7
8 //Prepare GraphQL operation...
9 AddPostMutation addPostMutation = AddPostMutation.builder().input(createPostInput).build();
10
11 awsAppSyncClient
12 .mutate(addPostMutation)
13 .enqueue(new GraphQLCall.Callback<AddPostMutation.Data>() {
14 @Override
15 public void onResponse(@Nonnull final Response<AddPostMutation.Data> response) {
16 addPostMutationResponse = response;
17 mCountDownLatch.countDown();
18 if (Looper.myLooper() != null) {
19 Looper.myLooper().quit();
20 }
21 }
22
23 @Override
24 public void onFailure(@Nonnull final ApolloException e) {
25 e.printStackTrace();
26 //Set to null to indicate failure
27 addPostMutationResponse = null;
28 mCountDownLatch.countDown();
29 if (Looper.myLooper() != null) {
30 Looper.myLooper().quit();
31 }
32 }
33 });
34
35 Looper.loop();
36
37 }
38}).start();
39
40try {
41 mCountDownLatch.await(60, TimeUnit.SECONDS);
42} catch (InterruptedException iex) {
43 iex.printStackTrace();
44}

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, it's offline mutation queue, the Apollo cache, and your application code.

Shows an architecture diagram on how the AppSync client interfaces with the network GraphQL calls

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 happens automatically on Android by using id as a common cache key to uniquely identify the objects. You can choose to change the cache key with the .resolver() method when creating the AWSAppSyncClient:

1AWSAppSyncClient.builder()
2 .context(context)
3 .awsConfiguration(awsConfiguration)
4 .resolver(new CacheKeyResolver() {
5 @Nonnull
6 @Override
7 public CacheKey fromFieldRecordSet(@Nonnull ResponseField field, @Nonnull Map<String, Object> recordSet) {
8 return (CacheKey) recordSet.get("myKey"); //Use "mykey" instead as your cache key
9 }
10
11 @Nonnull
12 @Override
13 public CacheKey fromFieldArguments(@Nonnull ResponseField field, @Nonnull Operation.Variables variables) {
14 return (CacheKey) field.resolveArgument("id", variables);
15 }
16 })
17.build();

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" by writing directly to the store. This is done by querying the store directly with client.query().responseFetcher() and passing in AppSyncResponseFetchers.CACHE_ONLY to pull the records for a specific query that you wish to update.

For example, the below code shows how you would update the CreateTodoMutation mutation from earlier by creating a optimisticWrite(CreateTodoInput createTodoInput) helper method that has the same input. This adds an item to the cache by first adding query results to a local array with items.addAll(response.data().listTodos().items()) followed by the individual update using items.add(). You commit the record with client.getStore().write(). This example uses a locally generated unique identifier which 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 onResponse() method of the top level mutation callback by again querying the store, removing the item and calling client.getStore().write().

1private void optimisticWrite(CreateTodoInput CreateTodoInput){
2 final CreateTodoMutation.CreateTodo expected =
3 new CreateTodoMutation.CreateTodo(
4 "Pet", //GraphQL Type name
5 UUID.randomUUID().toString(),
6 createTodoInput.name(),
7 createTodoInput.description());
8
9 final AWSAppSyncClient client = ClientFactory.appSyncClient();
10 final ListTodosQuery listTodosQuery = ListTodosQuery.builder().build();
11
12 client.query(listTodosQuery).responseFetcher(AppSyncResponseFetchers.CACHE_ONLY)
13 .enqueue(new GraphQLCall.Callback<ListTodosQuery.Data>() {
14 @Override
15 public void onResponse(@Nonnull Response<ListTodosQuery.Data> response) {
16 //Populate a copy of the query in the cache
17 List<ListTodosQuery.Item> items = new ArrayList<>();
18 if(response.data() != null){
19 items.addAll(response.data().listTodos().items());
20 }
21
22 //Add the newly created item to the cache copy
23 items.add(new ListTodosQuery.Item(expected.__typename(),
24 expected.id(), expected.name(), expected.description()));
25
26 //Overwrite the cache with the new results
27 ListTodosQuery.Data data = new ListTodosQuery.Data(new ListTodosQuery.ListTodos(
28 "ModelPetConnection", items, null
29 ));
30
31 client.getStore().write(listTodosQuery, data).enqueue(null);
32 Log.i(TAG, "Successfully added item to local store");
33 }
34
35 @Override
36 public void onFailure(@Nonnull ApolloException e) {
37 Log.e(TAG, "Failed to add item ", e);
38 }
39 });
40}

Usage in your application would be like the following:

1CreateTodoInput createTodoInput = CreateTodoInput.builder().
2 name("Use AppSync").
3 description("Realtime and Offline").
4 build();
5
6mAWSAppSyncClient.mutate(CreateTodoMutation.builder().input(createTodoInput).build())
7 .enqueue(mutationCallback);
8
9optimisticWrite(createTodoInput);

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 response.data().listTodos().items() array. A recommended best practice would be to create similar overloaded methods for optimisticWrite(UpdateTodoInput updateTodoInput) and optimisticWrite(DeleteTodoInput deleteTodoInput).

Offline mutations work by default and are available in memory, as well as through app restarts. The onResponse callback in mutations is received when the network is available and will be executed as long as the app wasn't closed. However if the app was closed or crashed, the persistentMutationsCallback will be called in the AWSAppSyncClient builder which has information about the mutation type and identifier. You should use this in your client initialization routine to protect against any unknown app behaviors such as application errors or user interference:

1private AWSAppSyncClient mAWSAppSyncClient = AWSAppSyncClient.builder()
2 .context(getApplicationContext())
3 .awsConfiguration(new AWSConfiguration(getApplicationContext()))
4 .persistentMutationsCallback(new PersistentMutationsCallback() {
5 @Override
6 public void onResponse(PersistentMutationsResponse response) {
7 if (response.getMutationClassName().equals("AddPostMutation")) {
8 // perform action here add post mutation
9 }
10 }
11
12 @Override
13 public void onFailure(PersistentMutationsError error) {
14 // handle error feedback here
15 }
16 })
17 .build();

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 when you call .awsConfiguration() on the AWSAppSyncClient builder.

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:

1private AWSAppSyncClient mAWSAppSyncClient = AWSAppSyncClient.builder()
2 .context(getApplicationContext())
3 .awsConfiguration(new AWSConfiguration(getApplicationContext()))
4 .build();

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 passing tokens from the AWSMobileClient to cognitoUserPoolsAuthProvider() like so:

1private AWSAppSyncClient mAWSAppSyncClient = AWSAppSyncClient.builder()
2 .context(getApplicationContext())
3 .awsConfiguration(new AWSConfiguration(getApplicationContext()))
4 .cognitoUserPoolsAuthProvider(new CognitoUserPoolsAuthProvider() {
5 @Override
6 public String getLatestAuthToken() {
7 try {
8 return AWSMobileClient.getInstance().getTokens().getIdToken().getTokenString();
9 } catch (Exception e){
10 Log.e("APPSYNC_ERROR", e.getLocalizedMessage());
11 return e.getLocalizedMessage();
12 }
13 }
14 }).build();

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}

Then pass the AWSMobileClient to credentialsProvider() like so:

1private AWSAppSyncClient mAWSAppSyncClient = AWSAppSyncClient.builder()
2 .context(context)
3 .awsConfiguration(new AWSConfiguration(getApplicationContext()))
4 .credentialsProvider(AWSMobileClient.getInstance())
5 .build();

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 (MyOIDCAuthProvider is just for example purposes):

1private AWSAppSyncClient mAWSAppSyncClient = AWSAppSyncClient.builder()
2 .context(context)
3 .awsConfiguration(new AWSConfiguration(getApplicationContext()))
4 .oidcAuthProvider(new OidcAuthProvider() {
5 @Override
6 public String getLatestAuthToken() {
7 return MyOIDCAuthProvider();
8 }
9 })
10 .build();
11
12private static String MyOIDCAuthProvider(){
13 // Fetch the JWT token string from OIDC Identity provider
14 // after the user is successfully signed-in
15 return "token";
16}

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.

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

awsconfiguration.json based client instantiation

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).

1AWSAppSyncClient client = AWSAppSyncClient.builder()
2 .context(getApplicationContext())
3 .awsConfiguration(new AWSConfiguration(getApplicationContext()))
4 .useClientDatabasePrefix(true)
5 .build();

The following code creates a client factory to retrieve the client based on the authorization mode: public (API Key) or private (AWS IAM).

1// AppSyncClientMode.java
2public enum AppSyncClientMode {
3 PUBLIC,
4 PRIVATE
5}
6
7// ClientFactory.java
8public class ClientFactory {
9
10 private static Map<AWSAppSyncClient> CLIENTS;
11
12 public static AWSAppSyncClient getAppSyncClient(AppSyncClientMode choice) {
13 return CLIENTS[choice];
14 }
15
16 public static void initClients(final Context context) {
17 AWSConfiguration awsConfigPublic = new AWSConfiguration(context);
18 CLIENTS[PUBLIC] = AWSAppSyncClient.builder()
19 .context(context)
20 .awsConfiguration(awsConfigPublic)
21 .useClientDatabasePrefix(true)
22 .build();
23
24 AWSConfiguration awsConfigPrivate = new AWSConfiguration(context);
25 awsConfigPrivate.setConfiguration("friendly_name_AWS_IAM");
26 CLIENTS[PRIVATE] = AWSAppSyncClient.builder()
27 .context(context)
28 .awsConfiguration(awsConfigPrivate)
29 .useClientDatabasePrefix(true)
30 .credentialsProvider(AWSMobileClient.getInstance())
31 .build();
32 }
33}

This is what the usage would look like.

1ClientFactory.getAppSyncClient(AppSyncClientMode.PRIVATE).query(fooQuery).execute();

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 CLIENTS[PRIVATE] using AWS_IAM authorization mode.

  2. Query the post through CLIENTS[PRIVATE] using AWS_IAM authorization mode.

  3. Query the post through CLIENTS[PUBLIC] using API_KEY authorization mode.

1apiKeyAppSyncClient.query(GetPostQuery.builder().id(id).build())
2 .responseFetcher(responseFetcher)
3 .enqueue(new GraphQLCall.Callback<GetPostQuery.Data>() {
4 @Override
5 public void onResponse(@Nonnull Response<GetPostQuery.Data> response) {
6 GetPost post = response.data().getPost();
7 post.id();
8 post.author();
9 post.title();
10 post.content();
11 post.version();
12
13 post.url(); // Null - because it's not authorized
14 post.ups(); // Null - because it's not authorized
15 post.downs(); // Null - because it's not authorized
16
17 if (response.hasErrors()) {
18 Log.d(TAG, response.errors().get(0).message()); // "Not Authorized to access url on type Post"
19 Log.d(TAG, response.errors().get(1).message()); // "Not Authorized to access ups on type Post"
20 Log.d(TAG, response.errors().get(2).message()); // "Not Authorized to access downs on type Post"
21 }
22 }
23
24 @Override
25 public void onFailure(@Nonnull ApolloException e) {
26 e.printStackTrace();
27 }
28 });

Code based client instantiation

You can use the AWSAppSyncClientBuilder as an alternative to using awsconfiguration.json.

1// AppSyncClientMode.java
2public enum AppSyncClientMode {
3 PUBLIC,
4 PRIVATE
5}
6
7// ClientFactory.java
8public class ClientFactory {
9
10 private static Map<AWSAppSyncClient> CLIENTS;
11
12 public static AWSAppSyncClient getAppSyncClient(AppSyncClientMode choice) {
13 return CLIENTS[choice];
14 }
15
16 public static void initClients(final Context context) {
17 AWSConfiguration awsConfigPublic = new AWSConfiguration(context);
18 CLIENTS[PUBLIC] = AWSAppSyncClient.builder()
19 .context(context)
20 .apiKey(new BasicAPIKeyAuthProvider(apiKey))
21 .serverUrl(serverUrl)
22 .region(region)
23 .clientDatabasePrefix("API_KEY")
24 .useClientDatabasePrefix(true)
25 .build();
26
27 CLIENTS[PRIVATE] = AWSAppSyncClient.builder()
28 .context(context)
29 .serverUrl(serverUrl)
30 .region(region)
31 .clientDatabasePrefix("AMAZON_COGNITO_USER_POOLS")
32 .useClientDatabasePrefix(true)
33 .cognitoUserPoolsAuthProvider(new CognitoUserPoolsAuthProvider() {
34 @Override
35 public String getLatestAuthToken() {
36 try {
37 String idToken = AWSMobileClient.getInstance().getTokens().getIdToken().getTokenString();
38 return idToken;
39 } catch (Exception e) {
40 e.printStackTrace();
41 return null;
42 }
43 }
44 })
45 .build();
46 }
47}

Clear cache

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

1try {
2 awsAppSyncClient.clearCaches(); // clear the queries, mutations and Delta Sync
3} catch (AWSAppSyncClientException e) {
4 e.printStackTrace();
5}

Selectively clears cache based on ClearCacheOptions.

1try {
2 awsAppSyncClient.clearCaches(
3 ClearCacheOptions.builder()
4 .clearQueries() // clear the query cache
5 .clearMutations() // clear the mutations queue
6 .clearSubscriptions() // clear the subscriptions metadata stored for Delta Sync
7 .build());
8} catch (AWSAppSyncClientException e) {
9 e.printStackTrace();
10}

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. The DeltaSync API manages writes to the Apollo cache for you, and all rendering in your app (such as from React components, Angular bindings) should be done through a read-only fetch.

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 can 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 client.sync() process.

Usage

1// Provides the ability to sync using a baseQuery, subscription, deltaQuery, and a refresh interval
2Cancelable handle = client.sync(baseQuery, baseQueryCallback,
3 subscription, subscriptionCallback,
4 deltaQuery, deltaQueryCallback,
5 20 * 60);
6
7//Stop DeltaSync
8handle.cancel();

The method parameters

  • baseQuery the base query to get the baseline state. (REQUIRED)
  • baseQueryCallback callback to handle the baseQuery results. (REQUIRED)
  • subscription subscription to get changes on the fly.
  • subscriptionCallback callback to handle the subscription messages.
  • deltaQuery the catch-up query
  • deltaQueryCallback callback to handle the deltaQuery results.
  • baseRefreshIntervalInSeconds time duration (specified in seconds) when the base query will be re-run to get an updated baseline state.
  • returnValue returns a Cancelable object that can be used later to cancel the sync operation by calling the cancel() method.

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

1//Performs sync only with base query
2client.sync(baseQuery, baseQueryCallback, baseRefreshIntervalInSeconds)
3
4//Performs sync with delta but no subscriptions
5client.sync(baseQuery, baseQueryCallback, deltaQuery, deltaQueryCallback,
6 baseRefreshIntervalInSeconds)

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 a Map object called allPosts to collect and manage the posts and a RecyclerView to power the UI.

Base Query and BaseQuery Callback In the Adapter object, create the BaseQuery and the BaseQuery Callback. You will use the listPosts query from the sample schema as your base query.

1//Setup the BaseQuery - you will use the ListPostsQuery as your base query
2Query listPostsQuery = ListPostsQuery.builder().build();

In the baseQueryCallback you will receive and process the results of listPosts. You will update the allPosts Map object with the query results and trigger the RecyclerView to refresh the contents of the view. The listPosts query cache will be automatically updated by the SDK.

1GraphQLCall.Callback listPostsQueryCallback = new GraphQLCall.Callback<ListPostsQuery.Data>() {
2 @Override
3 public void onResponse(@Nonnull final Response<ListPostsQuery.Data> response) {
4 if (response == null || response.data() == null ||
5 response.data().listPosts() == null ||
6 response.data().listPosts() == null ) {
7 Log.d(TAG, "List Posts returned with no data");
8 return;
9 }
10
11 Log.d(TAG, "listPostsQuery returned data. Iterating over the data");
12 display.runOnUiThread(new Runnable() {
13 @Override
14 public void run() {
15 for (ListPostsQuery.ListPost p: response.data().listPosts()) {
16 //Populate the allPosts map with the posts returned by the query.
17 //The allPosts map is used by the recycler view.
18
19 allPosts.put(p.id(), new ListPostsQuery.ListPost("Post",
20 p.id(), p.author(), p.title(), p.content(),
21 p.url(),p.ups(),p.downs(),
22 p.createdDate(),
23 p.aws_ds()));
24 }
25 //Trigger the view to refresh by calling notifyDataSetChanged method
26 notifyDataSetChanged();
27 }
28 });
29 }
30
31 @Override
32 public void onFailure(@Nonnull ApolloException e) {
33 Log.e(TAG, "ListPostsQuery failed with [" + e.getLocalizedMessage() + "]");
34 }
35 };

Subscription and Subscription callback Next, you will create a subscription to get notified whenever a change (Add, Update or Delete) happens to a post.

1//Setup Delta Post Subscription to get notified when a change
2 //(add, update, delete) happens on a Post
3 OnDeltaPostSubscription onDeltaPostSubscription = OnDeltaPostSubscription.builder().build();

In the subscription callback, you will handle the change by adding, deleting or updating the allPosts Map object and trigger the RecyclerView to refresh the contents of the view. You will also add the logic to update the query cache for the listPosts query.

1AppSyncSubscriptionCall.Callback onDeltaPostSubscriptionCallback =
2 new AppSyncSubscriptionCall.Callback<OnDeltaPostSubscription.Data>() {
3 @Override
4 public void onResponse(@Nonnull Response<OnDeltaPostSubscription.Data> response) {
5 Log.d(TAG, "Delta on a post received via subscription.");
6 if (response == null || response.data() == null
7 || response.data().onDeltaPost() == null ) {
8 Log.d(TAG, "Delta was null!");
9 return;
10 }
11
12 Log.d(TAG, "Updating post to display");
13 final OnDeltaPostSubscription.OnDeltaPost p = response.data().onDeltaPost();
14
15 display.runOnUiThread(new Runnable() {
16 @Override
17 public void run() {
18 // Delete the Post if the aws_ds has the DELETE tag
19 if ( DeltaAction.DELETE == p.aws_ds()) {
20 allPosts.remove(p.id());
21 }
22 // Add/Update the post otherwise
23 else {
24 allPosts.put(p.id(), new ListPostsQuery.ListPost("Post",
25 p.id(), p.author(), p.title(), p.content(),
26 p.url(),p.ups(), p.downs(),
27 p.createdDate(),
28 p.aws_ds()));
29 }
30
31 //Update the baseQuery Cache
32 updateListPostsQueryCache();
33
34 //Trigger the view to refresh by calling notifyDataSetChanged method
35 notifyDataSetChanged();
36 }
37 });
38 }
39
40 @Override
41 public void onFailure(@Nonnull ApolloException e) {
42 Log.e(TAG, "Error " + e.getLocalizedMessage());
43 }
44
45 @Override
46 public void onCompleted() {
47 Log.d(TAG, "Received onCompleted on subscription");
48 }
49 };

The updateListPostsQueryCache method will update the query cache of the listPosts query as shown below.

1private void updateListPostsQueryCache() {
2 List<ListPostsQuery.ListPost> items = new ArrayList<>();
3 items.addAll(allPosts.values());
4
5 ListPostsQuery.Data data = new ListPostsQuery.Data(items);
6 ClientFactory.getInstance(display.getApplicationContext()).getStore()
7 .write(listPostsQuery, data).enqueue(null);
8 }

Delta Query and Delta Query Callback Next you will setup the delta query. You will use the listPostsDelta query for the changes made to Posts. The SDK will keep track of when it was last run and will automatically pass in the appropriate value for lastSync to get the updates in an optimized manner.

1//Setup the Delta Query to get changes to posts incrementally
2 Query listPostsDeltaQuery = ListPostsDeltaQuery.builder().build();

In the listPostsDeltaQueryCallback, you will add, update, delete the changed Posts in the allPosts Map object and trigger the RecyclerView to refresh the contents of the view. You will also add the logic to update the query cache for the listPosts query.

1GraphQLCall.Callback listPostsDeltaQueryCallback = new GraphQLCall.Callback<ListPostsDeltaQuery.Data>() {
2 @Override
3 public void onResponse(@Nonnull final Response<ListPostsDeltaQuery.Data> response) {
4 if (response == null || response.data() == null || response.data().listPostsDelta() == null ) {
5 Log.d(TAG, "listPostsDelta returned with no data");
6 return;
7 }
8
9 //Add to the ListPostsQuery Cache
10 Log.d(TAG, "listPostsDelta returned data. Iterating...");
11 display.runOnUiThread(new Runnable() {
12 @Override
13 public void run() {
14 for (ListPostsDeltaQuery.ListPostsDeltum p: response.data().listPostsDelta() ) {
15 // Delete the Post if the aws_ds has the DELETE tag
16 if ( DeltaAction.DELETE == p.aws_ds()) {
17 allPosts.remove(p.id());
18 continue;
19 }
20
21 // Add or Update the post otherwise
22 allPosts.put(p.id(), new ListPostsQuery.ListPost("Post",
23 p.id(), p.author(), p.title(), p.content(),
24 p.url(),p.ups(), p.downs(),
25 p.createdDate(),
26 p.aws_ds()));
27 }
28
29 //Update the baseQuery Cache
30 updateListPostsQueryCache();
31
32 //Trigger the view to refresh by calling notifyDataSetChanged method
33 notifyDataSetChanged();
34 }
35 });
36 }
37
38 @Override
39 public void onFailure(@Nonnull ApolloException e) {
40 Log.e(TAG, "listPostsDelta Query failed with [" + e.getLocalizedMessage() + "]");
41 }
42 };

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

1Cancelable handle = client.sync(listPostsQuery, listPostsQueryCallback,
2 onCreatePostSubscription, onCreatePostCallback,
3 listPostsDeltaQuery, listPostsDeltaQueryCallback,
4 20 * 60 );

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 execute the baseQuery, setup the subscription and execute the delta Query.
  • Runs when the device that is running the app transitions from offline to online. Depending on the duration for which the device was offline ( i.e., > baseRefreshIntervalInSeconds), 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. To enable this, add the AWSAppSyncAppLifecycleObserver to the ProcessLifeCycle owner in the onCreate method of your main view as follows:
1import android.arch.lifecycle.ProcessLifecycleOwner;
2 import com.amazonaws.mobileconnectors.appsync.AWSAppSyncAppLifecycleObserver;
3
4 ...
5 ...
6
7 ProcessLifecycleOwner.get().getLifecycle().
8 addObserver(new AWSAppSyncAppLifecycleObserver());
  • Runs once every baseRefreshIntervalInSeconds as part of a periodic catch-up.