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

  • Install and configure Amplify CLI

  • A Flutter application targeting Flutter SDK >= 3.3.0 with Amplify libraries integrated

    The following are also required, depending on which platforms you are targeting:

    • An iOS configuration targeting at least iOS 13.0 and XCode version >=13.2
    • An Android configuration targeting at least Android API level 24 (Android 7.0) or above
    • Any browser supported by Flutter for Web (you can check the list of supported browsers here)
    • Any Windows OS meeting Flutter minimums
    • macOS version 10.15 or higher
    • Any Ubuntu Linux distribution meeting Flutter minimums
    • 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.18.0 <4.0.0"
3
4dependencies:
5 flutter:
6 sdk: flutter
7 amplify_flutter: ^1.0.0
8 amplify_api: ^1.0.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_api/amplify_api.dart';
2import 'package:amplify_flutter/amplify_flutter.dart';
3import 'package:flutter/material.dart';
4
5import 'amplifyconfiguration.dart';
6import 'models/ModelProvider.dart';
7
8class MyApp extends StatefulWidget {
9 const MyApp({super.key});
10
11
12 State<MyApp> createState() => _MyAppState();
13}
14
15class _MyAppState extends State<MyApp> {
16
17 void initState() {
18 super.initState();
19 _configureAmplify();
20 }
21
22 Future<void> _configureAmplify() async {
23 final api = AmplifyAPI(modelProvider: ModelProvider.instance);
24 await Amplify.addPlugin(api);
25
26 try {
27 await Amplify.configure(amplifyconfig);
28 } on Exception catch (e) {
29 safePrint('An error occurred configuring Amplify: $e');
30 }
31 }
32
33
34 Widget build(BuildContext context) {
35 return const MaterialApp(
36 home: Scaffold(
37 body: Center(
38 child: Text('Home'),
39 ),
40 ),
41 );
42 }
43}

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: