Page updated Feb 7, 2024

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 Android application targeting Android API level 24 (Android 7.0) or above

Configure API

To start provisioning API resources in the backend, go to your project directory and execute the command:

amplify add api
1amplify add api

Enter 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`
1? Please select from one of the below mentioned services:
2 `GraphQL`
3# The part below will show you some options you can change, if you wish to change any of them you can navigate with
4# your arrow keys and update any field, otherwise you can click on `Continue` to move on
5? Here is the GraphQL API that we will create. Select a setting to edit or continue
6 `Continue`
7? Choose a schema template:
8 `Single object with fields (e.g., “Todo” with ID, name, description)`
9? Do you want to edit the schema now?
10 `No`

Troubleshooting: The AWS API plugins do not support conflict detection. If AppSync returns errors about missing _version and _lastChangedAt fields, or unhandled conflicts, disable conflict detection. Run amplify update api, and choose Disable conflict detection. If you started with the Getting Started guide, which introduces DataStore, this step is required.

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 }
1type Todo @model {
2 id: ID!
3 name: String!
4 description: String
5}

To push your changes to the cloud, execute the command:

amplify push
1amplify push

Upon completion, amplifyconfiguration.json will be updated to reference provisioned backend resources. Note that this file should already be a part of your project if you followed the Project setup walkthrough.

Generate Todo Model class

To generate the Todo model, change directories to your project folder and execute the command:

amplify codegen models
1amplify codegen models

The generated files will be under the app/src/main/java/com/amplifyframework.datastore.generated.model directory. It is strongly advised not to put any hand written code in app/src/main/java/com/amplifyframework.datastore.generated directory as it gets re-generated each time codegen is run.

Install Amplify Libraries

Expand Gradle Scripts, open build.gradle (Module :app). You will already have configured Amplify by following the steps in the Project Setup walkthrough.

Add these libraries into the dependencies block:

dependencies { implementation 'com.amplifyframework:core:ANDROID_VERSION' implementation 'com.amplifyframework:aws-api:ANDROID_VERSION' }
1dependencies {
2 implementation 'com.amplifyframework:core:ANDROID_VERSION'
3 implementation 'com.amplifyframework:aws-api:ANDROID_VERSION'
4}

Click Sync Now.

Initialize Amplify API

Call Amplify.addPlugin() to initialize the Amplify API category followed by Amplify.configure().

Add the following code to your onCreate() method in your application class:

Amplify.addPlugin(new AWSApiPlugin());
1Amplify.addPlugin(new AWSApiPlugin());

Your class will look like this:

public class MyAmplifyApp extends Application { @Override public void onCreate() { super.onCreate(); try { // Add these lines to add the AWSApiPlugin plugins Amplify.addPlugin(new AWSApiPlugin()); Amplify.configure(getApplicationContext()); Log.i("MyAmplifyApp", "Initialized Amplify"); } catch (AmplifyException error) { Log.e("MyAmplifyApp", "Could not initialize Amplify", error); } } }
1public class MyAmplifyApp extends Application {
2 @Override
3 public void onCreate() {
4 super.onCreate();
5
6 try {
7 // Add these lines to add the AWSApiPlugin plugins
8 Amplify.addPlugin(new AWSApiPlugin());
9 Amplify.configure(getApplicationContext());
10
11 Log.i("MyAmplifyApp", "Initialized Amplify");
12 } catch (AmplifyException error) {
13 Log.e("MyAmplifyApp", "Could not initialize Amplify", error);
14 }
15 }
16}
Amplify.addPlugin(AWSApiPlugin())
1Amplify.addPlugin(AWSApiPlugin())

Your class will look like this:

class MyAmplifyApp : Application() { override fun onCreate() { super.onCreate() try { // Add these lines to add the AWSApiPlugin plugins Amplify.addPlugin(AWSApiPlugin()) Amplify.configure(applicationContext) Log.i("MyAmplifyApp", "Initialized Amplify") } catch (error: AmplifyException) { Log.e("MyAmplifyApp", "Could not initialize Amplify", error) } } }
1class MyAmplifyApp : Application() {
2 override fun onCreate() {
3 super.onCreate()
4
5 try {
6 // Add these lines to add the AWSApiPlugin plugins
7 Amplify.addPlugin(AWSApiPlugin())
8 Amplify.configure(applicationContext)
9
10 Log.i("MyAmplifyApp", "Initialized Amplify")
11 } catch (error: AmplifyException) {
12 Log.e("MyAmplifyApp", "Could not initialize Amplify", error)
13 }
14 }
15}
RxAmplify.addPlugin(new AWSApiPlugin());
1RxAmplify.addPlugin(new AWSApiPlugin());

Your class will look like this:

public class MyAmplifyApp extends Application { @Override public void onCreate() { super.onCreate(); try { // Add these lines to add the AWSApiPlugin plugins RxAmplify.addPlugin(new AWSApiPlugin()); RxAmplify.configure(getApplicationContext()); Log.i("MyAmplifyApp", "Initialized Amplify"); } catch (AmplifyException error) { Log.e("MyAmplifyApp", "Could not initialize Amplify", error); } } }
1public class MyAmplifyApp extends Application {
2 @Override
3 public void onCreate() {
4 super.onCreate();
5
6 try {
7 // Add these lines to add the AWSApiPlugin plugins
8 RxAmplify.addPlugin(new AWSApiPlugin());
9 RxAmplify.configure(getApplicationContext());
10
11 Log.i("MyAmplifyApp", "Initialized Amplify");
12 } catch (AmplifyException error) {
13 Log.e("MyAmplifyApp", "Could not initialize Amplify", error);
14 }
15 }
16}

Create a Todo

Todo todo = Todo.builder() .name("My first todo") .description("todo description") .build(); Amplify.API.mutate( ModelMutation.create(todo), response -> Log.i("MyAmplifyApp", "Added Todo with id: " + response.getData().getId()), error -> Log.e("MyAmplifyApp", "Create failed", error) );
1Todo todo = Todo.builder()
2 .name("My first todo")
3 .description("todo description")
4 .build();
5
6Amplify.API.mutate(
7 ModelMutation.create(todo),
8 response -> Log.i("MyAmplifyApp", "Added Todo with id: " + response.getData().getId()),
9 error -> Log.e("MyAmplifyApp", "Create failed", error)
10);
val todo = Todo.builder() .name("My first todo") .description("todo description") .build() Amplify.API.mutate(ModelMutation.create(todo), { Log.i("MyAmplifyApp", "Added Todo with id: ${it.data.id}") }, { Log.e("MyAmplifyApp", "Create failed", it) } )
1val todo = Todo.builder()
2 .name("My first todo")
3 .description("todo description")
4 .build()
5
6Amplify.API.mutate(ModelMutation.create(todo),
7 { Log.i("MyAmplifyApp", "Added Todo with id: ${it.data.id}") },
8 { Log.e("MyAmplifyApp", "Create failed", it) }
9)
val todo = Todo.builder() .name("My first todo") .description("todo description") .build() try { val response = Amplify.API.mutate(ModelMutation.create(todo)) Log.i("MyAmplifyApp", "Added Todo with id: ${response.data.id}") } catch (error: ApiException) { Log.e("MyAmplifyApp", "Create failed", error) }
1val todo = Todo.builder()
2 .name("My first todo")
3 .description("todo description")
4 .build()
5try {
6 val response = Amplify.API.mutate(ModelMutation.create(todo))
7 Log.i("MyAmplifyApp", "Added Todo with id: ${response.data.id}")
8} catch (error: ApiException) {
9 Log.e("MyAmplifyApp", "Create failed", error)
10}
Todo todo = Todo.builder() .name("My first todo") .description("todo description") .build(); RxAmplify.API.mutate(ModelMutation.create(todo)) .subscribe( response -> Log.i("MyAmplifyApp", "Added Todo with id: " + response.getData().getId()), error -> Log.e("MyAmplifyApp", "Create failed", error) );
1Todo todo = Todo.builder()
2 .name("My first todo")
3 .description("todo description")
4 .build();
5
6RxAmplify.API.mutate(ModelMutation.create(todo))
7 .subscribe(
8 response -> Log.i("MyAmplifyApp", "Added Todo with id: " + response.getData().getId()),
9 error -> Log.e("MyAmplifyApp", "Create failed", error)
10 );

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: