loading...
Cover image for Serverless Tutorial: Serverless GraphQL API
Lambda Store

Serverless Tutorial: Serverless GraphQL API

svenanderson profile image Sven Anderson ・3 min read

What is GraphQL?

When I first heard the GraphQL, I thought it should be the query language for Graph databases :) No it is not. GraphQL is a query language for your APIs. The following was the easiest definition for me to grasp it: GraphQL is an enhanced version of REST where the clients get the exact data with a single request instead of polling the whole objects with multiple requests. If you still have "why" questions, I strongly recommend you to watch the first 4 videos here.

Hello World, Serverless GraphQL

In this tutorial, I will write an AWS Lambda function which will query the backend (Redis) and return response to the client within GraphQL API. Because it is a hello-world type of application, it will not feature the real advantages of GraphQL, but it should be a good starting point if you are planning to serve GraphQL using AWS Lambda functions.

You can reach the source code in the git repo.

Prerequisites:

  • An AWS account for AWS Lambda functions.

  • Install AWS SAM CLI tool as described here to create and deploy the project.

  • A Lambda Store account for serverless Redis.

Create the project

We will use AWS SAM to create and deploy the project. Here the commands

  • Run sam init
  • 1 - AWS Quick Start Templates
  • 1 - nodejs12.x
  • Project name [sam-app]: serverless-graphql
  • 1 - Hello World Example

Building the API

We will use the graphql library so let's first install it. Inside hello-world folder, run:
cd hello-world
npm install --save graphql
Also we need a Redis client:
npm install --save redis

Now let's edit our function app.js as below:


const {
    graphql,
    GraphQLSchema,
    GraphQLObjectType,
    GraphQLString,
    GraphQLNonNull
} = require('graphql')

const redis = require("redis");

let redisClient = redis.createClient ({
    host : 'YOUR_LAMBDASTORE_HOST',
    port : 'YOUR_LAMBDASTORE_PORT',
    password: 'YOUR_LAMBDASTORE_PASSWORD'
});

const getGreeting = (city) => {
    return new Promise(function(resolve, reject) {
        redisClient.get(city, function(err, country) {
            redisClient.quit()
            resolve(`Hello ${city}, ${country || 'World'}!`)
        })
    });
};

const schema = new GraphQLSchema({
    query: new GraphQLObjectType({
        name: 'RootQueryType', 
        fields: {
            greeting: {
                args: {city: {name: 'city', type: new GraphQLNonNull(GraphQLString)}},
                type: GraphQLString,
                resolve: (parent, args) =>  getGreeting(args.city)
            }
        }
    }),
})

exports.lambdaHandler = (event, context, callback) => {
    graphql(schema, event.queryStringParameters.query)
        .then(
            result => callback(null, {statusCode: 200, body: JSON.stringify(result)}),
            err => callback(err)
        )
};

First we create the redis client. getGreeting function is a resolver which generates a response for a query. In our example getGreeting takes the city as parameter, queries the redis database to find the country. It returns Hello $city, $country.

lambdaHandler function is entry point for the AWS Lambda. It basically get result from the resolver and return response in accordance with GraphQL API.

Test the Application

Before testing the application let's insert some data to the Redis database. From Lambda Store console, select your database and click to Connect button. Copy the Redis CLI connection string and run it on a command line. Add some entries as below:
redis

Fortunately, we can run the application without deploying to AWS. First build the app then run start the API locally as below:
sam build
sam sam local start-api
The API should be running locally, check by
curl -G 'http://127.0.0.1:3000/hello' --data-urlencode 'query={greeting(city:"paris")}'
You should see:
{"data":{"greeting":"Hello paris, france!"}}

Deploy the Application

You can deploy your application to AWS using sam deploy --guided
After the deployment, you can check your AWS console if the Lambda function and API Gateway have been deployed properly. And, you can run:
curl -G 'YOUR_API_GATEWAY_URL' --data-urlencode 'query={greeting(city:"paris")}'
You should see:
{"data":{"greeting":"Hello paris, france!"}}

What's Next?

This a very simple intro to GraphQL using serverless functions. For more sophisticated applications you may need a more powerful GraphQL server such as Apollo. It can be deployed to AWS Lambda as described here.

Posted on by:

svenanderson profile

Sven Anderson

@svenanderson

Making the world serverless

Lambda Store

Lambda Store is the first the `serverless Redis` service. In this blog, Lambda Store engineering team shares their experiences on Cloud, AWS, Kubernetes, Redis and of course Lambda Store.

Discussion

markdown guide
 

For AWS GraphQL wouldnt you want to be using AppSync?
aws.amazon.com/appsync/

 

Yeah, it is another good alternative.