API (GraphQL)

Getting started

Amplify Flutter does not currently support the use of data models when making GraphQL calls. To make a GraphQL request, you must provide a GraphQL query or mutation document, along with any runtime data needed to resolve variables in the document.

In the future, Amplify Flutter will provide APIs that generate GraphQL requests directly from Dart-language data models.

You can learn more about the structure of a request from the GraphQL Query Language and AppSync documentation. To test out a few of your own requests, open the AppSync console using amplify console api and navigate to the Queries tab.

We have created a Github Issue to track this missing feature.

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 >= 1.20 (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:

amplify add api

amplify add api

Enter the following when prompted:

? Please select from one of the below mentioned services: `GraphQL` ? Provide API name: `apiName` ? Choose the default authorization type for the API: `API key` ? Enter a description for the API key: `description` ? After how many days from now the API key should expire (1-365): `7` ? Do you want to configure advanced settings for the GraphQL API `No, I am done.` ? Do you have an annotated GraphQL schema? `No` ? Choose a schema template: `Single object with fields (e.g., “Todo” with ID, name, description)` ? Do you want to edit the schema now? `No`

? Please select from one of the below mentioned services: `GraphQL` ? Provide API name: `apiName` ? Choose the default authorization type for the API: `API key` ? Enter a description for the API key: `description` ? After how many days from now the API key should expire (1-365): `7` ? Do you want to configure advanced settings for the GraphQL API `No, I am done.` ? Do you have an annotated GraphQL schema? `No` ? Choose a schema template: `Single object with fields (e.g., “Todo” with ID, name, description)` ? Do you want to edit the schema now? `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 DataStore for entire API. 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 }

type Todo @model { id: ID! name: String! description: String }

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

amplify push

amplify push

Enter the following when prompted:

? Do you want to generate code for your newly created GraphQL API `No`

? Do you want to generate code for your newly created GraphQL API `No`

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.

Install Amplify Libraries

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

dependencies: flutter: sdk: flutter amplify_flutter: '<1.0.0' amplify_api: '<1.0.0'

dependencies: flutter: sdk: flutter amplify_flutter: '<1.0.0' 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:

import 'package:amplify_flutter/amplify.dart'; import 'package:amplify_api/amplify_api.dart'; import 'amplifyconfiguration.dart'; class MyAmplifyApp extends StatefulWidget { @override void initState() { super.initState(); _configureAmplify(); } void _configureAmplify() async { // Add the following line to add API plugin to your app Amplify.addPlugin(AmplifyAPI()); try { await Amplify.configure(amplifyconfig); } on AmplifyAlreadyConfiguredException { print("Tried to reconfigure Amplify; this can occur when your app restarts on Android."); } } }

import 'package:amplify_flutter/amplify.dart'; import 'package:amplify_api/amplify_api.dart'; import 'amplifyconfiguration.dart'; class MyAmplifyApp extends StatefulWidget { void initState() { super.initState(); _configureAmplify(); } void _configureAmplify() async { // Add the following line to add API plugin to your app Amplify.addPlugin(AmplifyAPI()); try { await Amplify.configure(amplifyconfig); } on AmplifyAlreadyConfiguredException { print("Tried to reconfigure Amplify; this can occur when your app restarts on Android."); } } }

Create a Todo

try { String graphQLDocument = '''mutation CreateTodo(\$name: String!, \$description: String) { createTodo(input: {name: \$name, description: \$description}) { id name description } }'''; var variables = { "name": "my first todo", "description": "todo description", }; var request = GraphQLRequest<String>(document: graphQLDocument, variables: variables); var operation = Amplify.API.mutate(request: request); var response = await operation.response; var data = response.data; print('Mutation result: ' + data); } on ApiException catch (e) { print('Mutation failed: $e'); }

try { String graphQLDocument = '''mutation CreateTodo(\$name: String!, \$description: String) { createTodo(input: {name: \$name, description: \$description}) { id name description } }'''; var variables = { "name": "my first todo", "description": "todo description", }; var request = GraphQLRequest<String>(document: graphQLDocument, variables: variables); var operation = Amplify.API.mutate(request: request); var response = await operation.response; var data = response.data; print('Mutation result: ' + data); } on ApiException catch (e) { print('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:

next

Concepts

Next Page
Discord Logo
Amplify open source, documentation and community are supported by Amazon Web Services © 2020, Amazon Web Services, Inc. and its affiliates. All rights reserved. View the site terms and privacy policy.
    Flutter and the related logo are trademarks of Google LLC. We are not endorsed by or affiliated with Google LLC.