Page updated Jan 16, 2024

Set up Amplify GraphQL API

Amplify Flutter v0 is now in Maintenance Mode until July 19th, 2024. This means that we will continue to include updates to ensure compatibility with backend services and security. No new features will be introduced in v0.

Please use the latest version (v1) of Amplify Flutter to get started.

If you are currently using v0, follow these instructions to upgrade to v1.

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

  • Install and configure Amplify CLI
  • A Flutter application targeting Flutter SDK >= 2.10.0 (stable version) with Amplify libraries integrated
    • An iOS configuration targeting at least iOS 11.0
    • An Android configuration targeting at least Android API level 21 (Android 5.0) or above
    • For a full example please follow the project setup walkthrough

Configure API

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

1amplify add api

Enter the following when prompted:

1? Please select from one of the below mentioned services:
2 `GraphQL`
3# The part below will show you some options you can change, if you wish to change any of them you can navigate 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:

1type Todo @model {
2 id: ID!
3 name: String!
4 description: String
5}

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

1amplify push

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

Generate Todo Model class

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

1amplify codegen models

The generated files will be under the lib/models directory by default. They get re-generated each time codegen is run.

Install Amplify Libraries

Add the following dependencies to your pubspec.yaml file and install dependencies when asked:

1environment:
2 sdk: ">=2.15.0 <3.0.0"
3
4dependencies:
5 flutter:
6 sdk: flutter
7 amplify_flutter: ^0.6.0
8 amplify_api: ^0.6.0

Initialize Amplify API

To initialize the Amplify API category you call Amplify.addPlugin() method. To complete initialization call Amplify.configure().

Your code should look like this:

1import 'package:amplify_flutter/amplify_flutter.dart';
2import 'package:amplify_api/amplify_api.dart';
3import 'package:amplify_example_application/models/ModelProvider.dart';
4
5
6import 'amplifyconfiguration.dart';
7
8class MyApp extends StatefulWidget {
9
10 _MyAppState createState() => _MyAppState();
11}
12
13class _MyAppState extends State<MyApp> {
14
15 void initState() {
16 super.initState();
17 _configureAmplify();
18 }
19
20 Future<void> _configureAmplify() async {
21 final api = AmplifyAPI(modelProvider: ModelProvider.instance);
22 await Amplify.addPlugin(api);
23
24 try {
25 await Amplify.configure(amplifyconfig);
26 } on AmplifyAlreadyConfiguredException {
27 safePrint(
28 'Tried to reconfigure Amplify; this can occur when your app restarts on Android.');
29 }
30 }
31}

Create a Todo

1Future<void> createTodo() async {
2 try {
3 final todo = Todo(name: 'my first todo', description: 'todo description');
4 final request = ModelMutations.create(todo);
5 final response = await Amplify.API.mutate(request: request).response;
6
7 final createdTodo = response.data;
8 if (createdTodo == null) {
9 safePrint('errors: ${response.errors}');
10 return;
11 }
12 safePrint('Mutation result: ${createdTodo.name}');
13 } on ApiException catch (e) {
14 safePrint('Mutation failed: $e');
15 }
16}

Upon successfully executing this code, you should see an instance of todo persisted in your dynamoDB table.

To navigate to your backend, run amplify console api and choose GraphQL. This will open the AppSync console to your GraphQL service. Select Data Sources and select the Resource link in your TodoTable to bring you to the DynamoDB Console. Select the items tab to see the Todo object that has been persisted in your database.

Next steps

Congratulations! You've created a Todo object in your database. Check out the following links to see other Amplify API use cases: