Build & Deploy AWS Lambda GraphQL APIs: 2 Easy Steps

on API, AWS, AWS Lambda, Data Integration, Git, GraphQL, Node js, postman, Tutorials • April 6th, 2022 • Write for Hevo

AWS Lambda GraphQL

Organizations continuously update their applications and services to keep them up to date with the technology. Modern applications stream data using APIs while delivering smooth performance. Large websites and applications fetch huge volumes of data and to get exactly what data they need is a complex task. 

GraphQL is a language designed for handling APIs requests that enable users to query, access, and manipulate data through an intuitive and flexible syntax. AWS Lambda is a serverless technology that makes it easier for users to run code in response to events. AWS Lambda GraphQL Integration helps Developers manage thousands of files and business logic.

AWS Lambda GraphQL allows you to request only the data that is needed and a runtime for fulfilling those queries with your existing data. In this article, you will learn about the steps to set up AWS Lambda GraphQL Integration. Also, read how AWS Lambda GraphQL helps companies make blazing fast applications.

Table of Content

What is AWS Lambda?

AWS Lambda Logo - AWS Lambda GraphQL
Image Source

AWS Lambda is an event-driven, serverless computing service provided by Amazon Web Services that lets users run their code without provisioning and managing any infrastructure or servers. 

AWS Lambda runs the code in high availability compute infrastructure and manages all computing resources administration, maintenance, scaling, monitoring, and logging. Lambda allows users to run any type of application and service provided the code is in the language that Lambda supports.

Key Features of AWS Lambda

AWS Lambda is an excellent tool when there is a requirement for serverless computing. A few key features of AWS Lambda are listed below: 

  • Functions Defined as Container Images: AWS Lambda allows users to user-preferred container image tooling, workflows, and dependencies to build, test, and deploy Lambda functions.
  • Lambda Extensions: You can use Lambda extensions to augment your Lambda functions. For example, use extensions to integrate Lambda with your favorite tools for monitoring, observability, security, and governance.
  • Function Blueprints: AWS Lambda provides function blueprints that provide sample code to use AWS Lambda with other third-party applications. Users can easily use the blueprints to customize and deploy their application in AWS Lambda.
  • Database Access: AWS Lambda manages a pool of database connections and relays queries from a function.  It allows functions to reach high concurrency levels without disturbing Database connections.
  • File Systems Access: AWS Lambda supports file system access through mounting. It allows users to mount Amazon Elastic File System to access the content securely and at high concurrency.

To know more about AWS Lambda, click here.

What is GraphQL?

GraphQL logo - AWS Lambda GraphQL
Image Source

GraphQL is a query language built for APIs to query the existing data. GraphQL provides a complete description of API data that provides flexibility to ask for exactly what the client needs and nothing more, making it easier to evolve APIs over time and enabling powerful developer tools.

GraphQL isn’t tied to any specific database and storage engine, and hence it can query data from any Database as it is backed by existing code and the data.

Once the GraphQL server is up and running, users can submit the queries on the server, validating the query and executing them. The GraphQL server first checks a query to ensure it only refers to the types and fields defined and then runs the provided functions to produce a result.

For example, a GraphQL query like the below: 

{
  me {
    name
  }
}

Could produce the following JSON result:

{
  "me": {
    "name": "Luke Skywalker"
  }
}

Key Features of GraphQL

  • Fetching Data with a Single API Call: GraphQL allows users to retrieve the data from a single API call instead of the REST endpoint, which has individual endpoints to retrieve the data. 
  • No over and Under-Fetching Problems: GraphQL knows what precisely the client is requesting, and hence the response contains the exact data in the single request as opposed to REST responses, which are known for either containing too much data or not enough of it.
  • Detailed Error Messages: GraphQL provides detailed error messages that include all the resolvers and faulty parts of the queries.
  • API Evolution: GraphQL creates a uniform API across the entire application that solves the problem of API versioning and API evolution. Hence, the user can remove the deprecated fields later without impacting the schema and existing queries. GraphQL APIs give apps continuous access to new features and encourage cleaner, more maintainable server code by using a single, evolving version.

To know more about GraphQL, click here.

Simplify you ETL using Hevo’s No-code Data Pipelines

Hevo Data, a Fully-managed Data Pipeline platform, can help you automate, simplify & enrich your data replication process in a few clicks. With Hevo’s wide variety of connectors and blazing-fast Data Pipelines, you can extract & load data from 100+ Data Sources straight into your Data Warehouse or any Databases. To further streamline and prepare your data for analysis, you can process and enrich raw granular data using Hevo’s robust & built-in Transformation Layer without writing a single line of code!

Get Started with Hevo for Free

Hevo is the fastest, easiest, and most reliable data replication platform that will save your engineering bandwidth and time multifold. Try our 14-day full access free trial today to experience an entirely automated hassle-free Data Replication!

Prerequisites

Now that you have a basic understanding of AWS Lambda and GraphQL, it’s time to see how you can easily deploy a GraphQL server on AWS Lambda. But before proceeding with the AWS Lambda GraphQL Integration section, let’s have a look at the pre-requisites required listed below:

  • AWS account with access to IAM and Lambda.
  • Serverless installed on your machine.
  • Node.js v8.x or later.
  • git v2.14.1 or later.

Steps for AWS Lambda GraphQL Integration

In this section, you will go through the steps to set up AWS Lambda GraphQL Integration in which you will build a GraphQL Server and deploy it on AWS Lambda. The following steps for AWS Lambda GraphQL Integration are listed below:

Step 1: Building the GraphQL Server

Open the CLI and run the below commands to download and install some packages for AWS Lambda GraphQL Integration. 

mkdir serverless-orders-api && cd serverless-orders-api
git init
npm init -y
npm install apollo-server-lambda
npm install -D serverless-offline

Serverless-offline will help us to develop and test the application locally. The following steps to build the GraphQL server are listed below.

1. Setup the GraphQL Handler

Open the above-created project on any source code editor and look for the file named handler.js to modify it. Update the file as shown below to add resolvers and schema to the file to create a new Apollo server.

const { ApolloServer } = require('apollo-server-lambda');
const { resolvers } = require('./graphql/resolvers');
const { typeDefs } = require('./graphql/schema');

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

module.exports.graphqlHandler = server.createHandler({
  cors: {
    origin: '*',
    credentials: true,
  },
});

2. Setup the Schema

In this particular use case, we will be using the hardcoded value retrieved via GraphQL(as we are not using any database to link).

The schema file defines how our data looks and its type. Create a file named schema.js inside a new folder named graphql in the project’s root and paste the following content on it.

const { gql } = require('apollo-server-lambda');

module.exports.typeDefs = gql`
  type Orders {
    id: String!
    amount: Float!
    tax: Float!
    total: Float!
  }
  type Query {
    getOrders: [Orders]
  };

What makes Hevo’s ETL Process Best-In-Class

Providing a high-quality ETL solution can be a difficult task if you have a large volume of data. Hevo’s automated, No-code platform empowers you with everything you need to have for a smooth data replication experience.

Check out what makes Hevo amazing:

  • Fully Managed: Hevo requires no management and maintenance as it is a fully automated platform.
  • Data Transformation: Hevo provides a simple interface to perfect, modify, and enrich the data you want to transfer.
  • Faster Insight Generation: Hevo offers near real-time data replication so you have access to real-time insight generation and faster decision making. 
  • Schema Management: Hevo can automatically detect the schema of the incoming data and map it to the destination schema.
  • Scalable Infrastructure: Hevo has in-built integrations for 100+ sources (with 40+ free sources) that can help you scale your data infrastructure as required.
  • Live Support: Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.
Sign up here for a 14-day free trial!

3. Setup the Resolvers

Resolvers are the files that provide instructions to GraphQL about queries and how to return data. Create a resolver.js file under the graphql folder and paste the below content. This is a step to put database details to fetch data, but we will return some static data in this tutorial.

module.exports.resolvers = {
  Query: {
    getOrders: (_, args) => {
      const orders = [
        {
          id: '1977',
          amount: 10.0,
          tax: 0.5,
          total: 10.5,
        },
        {
          id: '1978',
          amount: 20.0,
          tax: 1.0,
          total: 21.0,
        },
        {
          id: '1979',
          amount: 30.0,
          tax: 1.5,
          total: 31.5,
        },
      ];

      return orders;
    },
  },
};

4. Setup the severless.yml File

From the serverless-offline, modify the serverless.yml file and paste the following content into it.

service: serverless-graphql

plugins:
  - serverless-offline

provider:
  name: aws
  runtime: nodejs12.x
  stage: ${opt:stage, 'dev'}
  region: us-east-1
  memorySize: 128

functions:
  graphql:
    handler: handler.graphqlHandler
    events:
    - http:
        path: graphql
        method: ANY
        cors: true

5. Testing Locally

Now that we have everything in place, let’s run the GraphQL server locally. Go to the root directory of the project and there tun the following command given below.

serverless offline

Open postman or any API testing tool and use the url – http://localhost:3000/dev/graphql to test the query for AWS Lambda GraphQL Integration.

Step 2: Deploying to AWS

Once the local query is tested successfully, we can deploy AWS Lambda GraphQL. To deploy GraphQL on AWS, you need to have an active AWS account with sufficient privileges to access IAM and Lambda.

Deploying AWS Lambda GraphQL is a pretty straightforward process. On the console, run the below command to deploy to AWS – 

serverless deploy

If the deployment of AWS Lambda GraphQL goes well, you will see some output of AWS Lambda GraphQL Integration similar to the one shown below.

Deploy AWS Lambda GraphQL - AWS Lambda GraphQL
Image Source

Once the AWS Lambda GraphQL deployment is successful, let’s test the newly created AWS endpoint in Postman. You can provide the following POST request body, and the response of the AWS Lambda GraphQL API call will have the data associated with it. You will get the endpoint details in the success message in the terminal.

query {
 orders {
   id
   amount
   tax
   total
 }
}
Testing API on Postman - AWS Lambda GraphQL
Image Source

That’s it! You have completed the AWS Lambda GraphQL Integration in which you built a GraphQL server and deployed it using AWS Lambda.

Conclusion

In this article, you learnt about AWS Lambda, GraphQL, and how to build a GraphQL server locally and then deploy it to AWS Lambda using AWS serverless, which is a pretty straightforward task. You went through the detailed steps for AWS Lambda GraphQL Integration using an example. AWS Lambda is a widely used serverless technology and it is easy to use. 

Get Started with Hevo for Free

Companies need to analyze their business data stored in multiple data sources. Data needs to be loaded from data sources such as AWS S3 Bucket to the Data Warehouse to get a holistic view of the data. Hevo Data is a No-code Data Pipeline solution that helps to transfer data from 100+ data sources to desired Data Warehouse. It fully automates the process of transforming and transferring data to a destination without writing a single line of code.

Want to take Hevo for a spin? Sign Up  here for a 14-day free trial and experience the feature-rich Hevo.

Share your experience of learning about running AWS Lambda GraphQL Integration in the comments section below!

No-code Data Pipeline For your Data Warehouse