AWS AppSync GraphQL APIs to invoke Lambda function

Muhammad Shakeel
6 min readFeb 6, 2022

--

AWS AppSync is a managed serverless GraphQL service that simplifies application development by letting you create a flexible API to securely access, manipulate, and combine data from one or more data sources with a single network call. With AppSync, developers can build scalable applications on a range of data sources, including Amazon DynamoDB NoSQL tables, Amazon Aurora Serverless relational databases, Amazon OpenSearch Service (successor to Amazon Elasticsearch Service) clusters, HTTP APIs, and serverless functions powered by AWS Lambda.

AWS AppSync is a new service that enables developers to manage and synchronize mobile app data in real-time across devices and users but still allows the data to be accessed and altered when the mobile device is in an offline state.

AppSync GraphQL API is divided into three-part :

  • GraphQL schema
  • Data sources
  • Resolvers

GraphQL schema

A GraphQL schema is a description of the data clients can request from a GraphQL API. It also defines the queries and mutation functions that the client can use to read and write data from the GraphQL server

Data sources

DataSource resource creates data sources for resolvers in AWS AppSync to connect to, such as Amazon DynamoDB, AWS Lambda, and Amazon OpenSearch Service. Resolvers use these data sources to fetch data when clients make GraphQL calls.

Resolvers

Data sources and resolvers are how AWS AppSync translates GraphQL requests and fetches information from your AWS resources. AWS AppSync has support for automatic provisioning and connections with certain data source types.

Read More: https://docs.aws.amazon.com/appsync/latest/devguide/quickstart.html

Lambda function

A lambda function is a small anonymous function. AWS Lambda is a serverless computing service provided by Amazon Web Services (AWS). Users of AWS Lambda create functions, self-contained applications written in one of the supported languages and runtimes, and upload them to AWS Lambda, which executes those functions in an efficient and flexible manner.

I have posted a story on Lambda functions and Lambda layers. In which I have defined How can create lambda functions and lambda layers. I have tried to highlight the utilization of the lambda layer and the benefits of the layer.

Lambda functions and Lambda layers See the full story before going on

Create the AppSync API

Sign in to the AWS Management Console and open the AppSync console.

  1. In the Dashboard, choose to Create API
  2. In the bottom section list of samples, verify that Event App is selected. If it isn’t, select it. and choose Start.
  3. Enter a friendly name for your API.
  4. Choose Create and then wait for the provisioning process to finish.

After finishing all, your API dashboard look like

AppSync API

Let's create Schema

On the left side of the console, choose Schema to view the designer.

The designer has your sample Events schema loaded. The code editor has linting and error-checking capabilities that you can use when you write your own apps.

The right side of the console shows the GraphQL types that have been created and resolvers on different top-level types, such as queries.

Designing Schema

Creating an Empty Schema: Schema files are text files, usually named schema.graphql. You can create this file and submit it to AWS AppSync by using the CLI or navigating to the console and adding the following under the Schema page:

schema { }

Adding a Root Query Type: A GraphQL schema must have a root query type, so we add a root type named Query with a single inokeSampleFunction a field that returns sample function response. we can also pass parameters or a list of parameters. For now, we just pass a single parameter myName.

schema {
query:Query
}
type Query {
invokeSampleFunction(myName: String): String
}

Now Save Schema. Your schema and resolver section looks like

Now we need to attach Attach Resolver to invokeSampleFunction Field. Choose Attach and you will land on a new page where we attach resolver. But before that, we must have a datasource. You will notice that there is no Datasource.

Lambda functions and Lambda layers See the full story and setup lambda and layer before going on

Let's create Datasource, click on Add Datasource link and you will see a new window.

  1. Give your data source a friendly name, such as sampleFUnctionDatasource.
  2. Choose Aws Lambda Function as the type.
  3. Choose the appropriate region.
  4. Select or putt sampleFunction ARN in Function ARN filed.
  5. Default selected New role and Create.

Your Datasource window looks like

Now go to schema and attach resolver to query filed invokeSampleFunction under Resolvers section.

Select Datasource under the section Resolver for Query.invokeSampleFunction and Save Resolver.

Now go to the Queries under the AWS AppSync tab of your API.

You will seeinvokeSampleFunction it under the Explorer section. Check on invokeSampleFunction and then check the parameter myName and give here your name.

Now finally we invoke the sample Lambda function, click the orange play button. You will see the response from your Lambda working fine.

We a little bit change our lambda script to check to give myName parameter is working fine.

Before changing Lambda code

const { RandomPicture } = require('random-picture');
const { getDirection } = require("/opt/imageDimension");
exports.handler = async (event) => {
const res = await RandomPicture();
return {
"Dimension": getDirection(res.width, res.height),
url: res.url,
author: res.author,
};
};

After changed code

const { RandomPicture } = require('random-picture');
const { getDirection } = require("/opt/imageDimension");
exports.handler = async (event) => {
const name = event.arguments.myName;
const res = await RandomPicture();
return {
"Dimension": getDirection(res.width, res.height),
url: res.url,
author: res.author,
myName : name
};
};

Now again test appSync query, and pass your name or any random string you will see your parameter in query response under the key myName.

It’s time to say goodbye, hope you will enjoy the story. If you have any questions regarding appsync, Lambda, Lambda layers, or other AWS services, feel free to contact me I will facilitate as much as I can.

--

--

Muhammad Shakeel

Exceptionally creative and dependable Professional Level Web and Mobile Developer with a stellar customer service record and superb work ethic. AWS | JavaScript