Empower Your API Development: How to use AWS Lambda as Data Source In AWS GraphQL, AppSync(Part#2)

Imranburki
3 min readMay 10, 2024

--

Welcome back! If you’re just joining us, this post is the second part of a series dedicated to exploring AWS GraphQL. In the previous installment, we delved into the fundamentals of AWS GraphQL, its significance, and the key components that make it tick. If you missed it, I highly recommend giving it a read to get up to speed (part1).

In this part, we’re diving deeper into the practical aspects of AWS GraphQL by exploring how to leverage AWS Lambda as a data source — a powerful combination that can supercharge your GraphQL API development. Following is the basic architecture of GraphQL and AppSync

sI’ve uploaded the code for GraphQL API, including Lambda function integrations, to my GitHub repository. You can find the full implementation, along with detailed instructions, here.

step1. Create a new project in your favorite programming language using aws cdk command (I’m using python).

mkdir gqlTestproject
cd gqlTestproject
cdk init app --language python

After successfully creating your project, next activate python virtual environment and install requirements using command

source .venv/bin/activate
python -m pip install -r requirements.txt

step2. Define GraphQl schema. As for simplicity Icreated below schema in a file named “graphqlschema.gql”

setp3. Create a GraphQl API using AWS AppSync using schema created in step#2. For security purpose use API_KEY. There are many other
options to prevent unauthorized access like AWS Ampliy, IAM etc. But for simplicity we are using APIKEY

gqpapi=self.createGQLApi('testgqlApi','demoapi','./graphql/graphqlschema.gql')

for more detail visit aws cdk doc

set4. Create Lambda function. For demonstration purpose I defined a simple lambda function in a folder ‘resources’, one can create lambda function according to need.

Call this lambda in main stack file as

step5. Create/Add Lambda we created in step#4 as GraphQl DataSource. Here we have to specify the lambda function which will be used as Datasource.

step6. Create Resolver for each Query field

setp6. Go to aws console and head over the AppSync. on left hand sidebar there is option for ‘setting’, click on it and get GraphQL endpoint and scroll down there will be and APIKEY in ‘Primay auth mode’
section.

setp6. copy Graphql endpoint and api key. open Postman set Post method and insert GraphQl endpoint and from body select GraphQL. in Header section, set two keys value pairs
1.x-api-key====> <APIKEY copied>
2.Content-Type====> application/graphql

Now, if you get desired response then it mean it worked successfully.

Hence, In this blog we learned how to use AWS Lambda as data source for AWS AppSync to build AWS GraphQL APIs.

--

--