Page updated Jan 16, 2024

Set up Amplify REST API

The Amplify API category provides an interface for making requests to your backend. The Amplify CLI deploys REST APIs and handlers using Amazon API Gateway and AWS Lambda.

Goal

To setup and configure your application with Amplify API to make requests to your API Gateway and trigger the lambda function using authorization provided by Amplify Auth.

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 `REST`
3? Provide a friendly name for your resource to be used as a label for this category in the project:
4 `api`
5? Provide a path (e.g., /book/{isbn}):
6 `/todo`
7? Choose a Lambda source
8 `Create a new Lambda function`
9? Provide a friendly name for your resource to be used as a label for this category in the project:
10 `todo`
11? Provide the AWS Lambda function name:
12 `todo`
13? Choose the function runtime that you want to use:
14 `NodeJS`
15? Choose the function template that you want to use:
16 `Serverless ExpressJS function (Integration with API Gateway)`
17? Do you want to access other resources created in this project from your Lambda function?
18 `No`
19? Do you want to invoke this function on a recurring schedule?
20 `No`
21? Do you want to edit the local lambda function now?
22 `No`
23? Restrict API access
24 `No`
25? Do you want to add another path?
26 `No`

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

1amplify push

Upon completion, amplifyconfiguration.dart should be updated to reference provisioned backend storage 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. Please keep in mind that Auth plugin is needed for IAM authorization mode, which is default for REST API:

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
9 amplify_auth_cognito: ^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_flutter/amplify_flutter.dart';
2import 'package:amplify_api/amplify_api.dart';
3import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
4import 'package:flutter/material.dart';
5
6import 'amplifyconfiguration.dart';
7
8void main() {
9 runApp(MyApp());
10}
11
12class MyApp extends StatefulWidget {
13
14 _MyAppState createState() => _MyAppState();
15}
16
17class _MyAppState extends State<MyApp> {
18
19 void initState() {
20 super.initState();
21 _configureAmplify();
22 }
23
24 Future<void> _configureAmplify() async {
25 // Add the following line to add API plugin to your app.
26 // Auth plugin needed for IAM authorization mode, which is default for REST API.
27 final auth = AmplifyAuthCognito();
28 final api = AmplifyAPI();
29 await Amplify.addPlugins([api, auth]);
30
31 try {
32 await Amplify.configure(amplifyconfig);
33 } on AmplifyAlreadyConfiguredException {
34 safePrint(
35 'Tried to reconfigure Amplify; this can occur when your app restarts on Android.');
36 }
37 }
38
39 Future<void> onTestApi() async {
40 // Edit this function with next steps.
41 }
42
43
44 Widget build(BuildContext context) {
45 return MaterialApp(
46 home: Scaffold(
47 body: Padding(
48 padding: const EdgeInsets.all(20.0),
49 child: ElevatedButton(
50 onPressed: onTestApi,
51 child: const Text('Rest API'),
52 ),
53 ),
54 ),
55 );
56 }
57}

Make a POST Request

Send a POST request with a JSON body.

1Future<void> postTodo() async {
2 try {
3 final restOperation = Amplify.API.post(
4 'todo',
5 body: HttpPayload.json({'name': 'Mow the lawn'}),
6 );
7 final response = await restOperation.response;
8 print('POST call succeeded');
9 print(response.decodeBody());
10 } on ApiException catch (e) {
11 print('POST call failed: $e');
12 }
13}

To navigate to your backend, go to the API Gateway console and select the API. The name of the API corresponds to the friendly name of the resource to be used as a label you specified earlier in the CLI steps.

Next steps

Congratulations! You've made a call to your API Gateway and triggered your Lambda function. Check out the following links to see other Amplify API use cases: