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
Amplify Flutter requires a minimum target platform for iOS (13.0), Android (API level 24), and macOS (10.15). Additional setup is required for some target platforms. Please see the platform setup guide for more details on platform specific setup.
Configure API
To start provisioning API resources in the backend, go to your project directory and execute the command:
amplify 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`
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}
To push your changes to the cloud, execute the command:
amplify 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:
amplify 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:
dependencies: flutter: sdk: flutter amplify_flutter: ^2.0.0 amplify_api: ^2.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:
import 'package:amplify_api/amplify_api.dart';import 'package:amplify_flutter/amplify_flutter.dart';import 'package:flutter/material.dart';
import 'amplifyconfiguration.dart';import 'models/ModelProvider.dart';
class MyApp extends StatefulWidget { const MyApp({super.key});
State<MyApp> createState() => _MyAppState();}
class _MyAppState extends State<MyApp> { void initState() { super.initState(); _configureAmplify(); }
Future<void> _configureAmplify() async { final api = AmplifyAPI( options: APIPluginOptions(modelProvider: ModelProvider.instance), ); await Amplify.addPlugin(api);
try { await Amplify.configure(amplifyconfig); } on Exception catch (e) { safePrint('An error occurred configuring Amplify: $e'); } }
Widget build(BuildContext context) { return const MaterialApp( home: Scaffold( body: Center( child: Text('Home'), ), ), ); }}
Create a Todo
Future<void> createTodo() async { try { final todo = Todo(name: 'my first todo', description: 'todo description'); final request = ModelMutations.create(todo); final response = await Amplify.API.mutate(request: request).response;
final createdTodo = response.data; if (createdTodo == null) { safePrint('errors: ${response.errors}'); return; } safePrint('Mutation result: ${createdTodo.name}'); } on ApiException catch (e) { safePrint('Mutation failed: $e'); }}
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: