How to call a Lambda Function via API Gateway on Aws Services from the mobile client by using Flutter and Amplify?

Ugur Can
DFDS Development Center Istanbul
7 min readDec 13, 2021

Part III: Accessing Api Gateway using Flutter and Amplify.

In the previous part of my article, we created an endpoint on Aws Services and opened this endpoint to the outside world. In this section, we will write an application that accesses this endpoint using flutter and amplify.

  • Run Visual Studio Code.
  • Open a new Terminal screen by selecting “New Terminal” from the Terminal menu.
  • Go to the folder where you will create the project and run the

flutter create project-name” command.

  • After your project is created, run Visual Studio Code from the project folder.
  • Open a new powershell screen by selecting “New Terminal” from the terminal menu.
  • Install Amplify by running the command;

curl -sL https://aws-amplify.github.io/amplify-cli/install-win -o .\install.cmd && .\install.cmd”.

  • After the installation is finished, “amplify.exe” will be in the “%USER%\.amplify\bin” folder. At the end of the installation, the script will tell you that it has uploaded this folder to “PATH”. However, sometimes you may have problems running this file from this folder. Therefore, my advice to you is to call each time by specifying the folder address.
  • Before configuring the amplify, please update your amplify by running the “amplify upgrade” command.
  • After your update is complete, run the “amplify configure” command. The Configure command is the command that allows you to define your project’s AWS services to access. After the command runs, it will ask you to do some things in order;
  • Login to Aws services with your browser.
    - Choose in which region you will operate.
    - Enter the name of the user you will use for Aws services of your project. This will create the user on the IAM service.
    - You can view the “AdministratorAccess-Amplify” authorization in the user’s authorization definitions, and you can define other authorizations you want to grant here.
    - Define a Secret Access Key for the user from the Security Credentials tab and copy it together with the “Access Key ID” for later use.
    - Save changes and update user information.
  • Return to the Visual Studio Code Terminal.
  • Copy the Access Key Id you copied to the terminal. Your Access Key ID and Secret Access Key information will be masked to prevent third parties from seeing it during copying.
  • This information will be saved in the credentials file under the “%USER%\.aws” folder.
  • Save your Amplify profile with a name and complete its configuration.
  • Run the “amplify init” command on the terminal screen. The init command allows you to run the amplify library that you have installed and configured with your project in your project.
  • Give your Amplify project a name.
  • . If you accept the installation details displayed for your project. Press the “Y” key and press Enter.
  • Select “Aws Profile” as the authentication method and press Enter and select the user profile that has just been created from the list.
  • After this stage, “Amplify” folder will be created under the project folder and all libraries required to access Aws services will be installed.
  • After the installation is complete, you can choose how to access Aws services and continue with the installation. If you want to create a new end-point for a new API, you can continue with the “amplify add api” command from here. However, we skip this part as we will be accessing an existing API and endpoint.
  • After the init process is complete, Amplify will create the “amplifyconfiguration.dart” file under the “lib” folder of your project. Open this file.
  • You will see a JSON object in the opened file. This JSON is the file containing the definitions for you to access and use AWS services.
    u. “awsAPIPlugin” under “plugins” is the plugin that will take us to Aws API Gateway.
  • The data containing the project name you have defined will be the definitions we will use to access API Gateway. From the data you created and saved in the previous section;
    - Copy the “Invoke URL” value that you copied and saved in the “Stages” section as the “endpoint” value.
    - Specify your “region”.
    - Specify “API_KEY” as the “authorizationType” value.
    - Again, enter the “API key” value that you copied and saved in the previous section as the “apiKey” value.
    - Save the file.
  • Open the “pubspec.yaml” file in the project folder. And in the “dependencies” section you will use for your project. Save the “Amplify” packages.
  • After the packages are written and the file is saved, Visual Studio Code automatically downloads and installs these packages.
  • It makes it ready to use.Open the “main.dart” file under the “lib” folder under your project folder and add the package names to the list at the top of the page as a reference.
  • Create a method named “_configureAmplify”. This method will be used to access the amplify libraries and to access your plugins definitions in the “amplifyconfiguration.dart” file. Make sure this method works by adding the “main” method. If the build does not give an error when you get it, everything is fine.
void main() {
runApp(const MyApp());
_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 {
throw new Exception('Amplify configuration error.');
}
}
  • In the project, create a new dart file of your choice. Create a new class and a method inside this dart file. With this class and method, you will connect to Api Gateway on Aws with amplify.
import 'dart:convert';
import 'dart:typed_data';
import 'package:amplify_api/amplify_api.dart';class HelloWorld {
Future<String> getHelloWorldMessageFromApi() async {
var requestObject = {};
var encodedRequestObject = jsonEncode(requestObject); RestOptions restOptions = RestOptions(
apiName: "HelloWorldApi",
path: '/show-hello-world-message',
body: Uint8List.fromList(
encodedRequestObject.codeUnits,
),
);
var res = AmplifyAPI().post(restOptions: restOptions); RestResponse response = await res.response; return String.fromCharCodes(response.data);
}
}
  • In the project I used as an example, I preferred to use the code structure below. You can use this as a starter if you want, or you can continue in another way yourself. Below I will explain for what purpose I will use certain objects;
    - I will keep the object “requestObject” that will be sent to the server as a body. Since there is no data to post in this example, I leave it blank.
    - With “jsonEncode” I converted the object as a string to the encoded “encodedRequestObject” object.
    - Since we selected Rest as the endpointType in the config in the “amplifyconfiguration.dart” file, I created the “RestOptions” object. While filling the data here;
    You should use the plugin name in the config as the apiName.
    As that path, you must enter your url in the endpoint without the stage address.
    o You need to convert the “encodedRequestObject” string file that you created as Body to “Uint8List” type.
    - Post the “restOptions” object you have created using the “AmplifyAPI().post” command.
    - You can convert the return value back to string using “String.fromCharCodes” and use it as you want from now on.
  • Give the class you created as a reference to the place where you will run it and call the method.
class _MyHomePageState extends State<MyHomePage> {
var _helloWorldMessage = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
_helloWorldMessage,
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
var helloWorld = HelloWorld();
var message = await helloWorld.getHelloWorldMessageFromApi();
setState(() {
_helloWorldMessage = message;

});
},
tooltip: 'Get Message',
child: const Icon(Icons.add),
),
);
}
}
  • It will access Aws using Method amplify and run the Lambda function through API Gateway and return the result to you.
    dd. It is possible that you may encounter some errors when you run the program. I will try to help you with a few of them.
    - One of the errors you will encounter is “The plugin amplify_api requires a higher Android SDK Version” error that may appear on Android-loaded devices.

To fix this error;
- Go to the “android\app” folder under your project and open the “buid.gradle” file.
- Update the “minSdkVersion” version with the value 21 in the “defaultConfig” data under the “android” object.

  • Build and run your project.
  • Click to plus button.
  • That’s it! You made it!

One of the errors you may encounter while running your Amplify project is the “Amplify plugin was not added” error. The reason for this error is that “Amplify” currently only supports Ios and Android operating systems. Amplify does not work in environments such as web and Windows.

It has been a long article and series, I hope I was able to help you. For your questions and comments, you can reach me at ugurcan@gmail.com.

Helpful Links

--

--