How to Build a Serverless GraphQL API Endpoint? | 5 Easy Steps

on API, GraphQL • May 20th, 2022 • Write for Hevo

serverless graphql: FI

APIs (Application Programming Interfaces) facilitate communication between different software systems. They can be used to transfer data from one system to another. Serverless architecture can provide a scalable, fast, and reliable way of working with APIs. After deploying your API to cloud service providers such as AWS, you can forget about server administration and focus on code. 

GraphQL is a query language for simplifying client-server interactions. It has a declarative data fetching feature that makes it very efficient.

In this article, you will be discussing how to build a serverless GraphQL API endpoint and deploy it to AWS. 

Table Of Contents

Prerequisites

This is what you need for Building a Serverless GraphQL API Endpoint:

  • An AWS Account. 
  • AWS CLI. 

What is an API?

serverless graphql: what is an api
Image Source

A connection between computers or computer programs is known as an Application Programming Interface (API). It’s a type of software interface that provides a service to other programs. An API specification is a document or standard that describes how to create or use a connection or interface. An API is implemented or exposed by a computer system that meets this standard. The term API can be used to refer to either the specification or the implementation.

An application programming interface, unlike a user interface, connects computers or pieces of software. It is not intended to be used directly by anyone (the end-user) other than a software programmer. An API is made up of various components that serve as tools or services for programmers. A program or programmer who uses one of these parts is said to be calling that section of the API. Subroutines, methods, requests, and endpoints are all terms used to describe the API’s calls. An API specification describes how to use and implement these calls.

One of the goals of APIs is to hide the internal workings of a system, exposing only the parts that a programmer will use and keeping them consistent even if the internal workings change. An API can be tailored to a specific pair of systems or it can be a shared standard that allows for system interoperability.

An API is a set of rules that describe how computers and applications interact. APIs are a data transfer layer that sits between an application and a web server.

An API works like this:

  • An API call, also known as a request, is initiated by a client application to retrieve data. This request contains a request verb, headers, and, in some cases, a request body, and is sent from an application to the web server via the API’s Uniform Resource Identifier (URI).
  • The API contacts the external program or webserver after receiving a valid request.
  • The API receives a response from the server that contains the requested data.
  • The data is returned to the application that is requested via the API.
  • While the data transfer method varies depending on the web service, the requests and responses are all handled by an API. APIs are designed for computers or applications to use, whereas user interfaces are designed for humans to use.
  • APIs are designed to provide security because their role as a middleman allows for the abstraction of functionality between two systems—the API endpoint decouples the consuming application from the infrastructure that provides the service. To reduce the risk of server attacks, API calls typically include authorization credentials, and an API gateway can limit access to minimize security threats. Additionally, HTTP headers, cookies, and query string parameters provide additional security layers to the data during the exchange.

Simplify ETL Using Hevo’s No-Code Data Pipeline

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 Data Warehouses, 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!

What is GraphQL?

serverless graphql: graphql logo
Image Source

GraphQL is an open-source data query and manipulation language for APIs, as well as a runtime for executing queries on pre-existing data. Facebook developed GraphQL internally in 2012 before making it public in 2015. The GraphQL project was moved from Facebook to the newly established GraphQL Foundation, which is hosted by the non-profit Linux Foundation, on November 7, 2018. Since 2012, GraphQL’s rise has closely followed Lee Byron’s adoption timeline. Byron wants GraphQL to be ubiquitous across all web platforms.

It describes a methodology for creating web APIs and compares and contrasts REST and other web service architectures. It allows clients to specify the data structure they require, and the server responds with the same structure, preventing the server from returning excessively large amounts of data. However, this has implications for the effectiveness of query result caching on the web. The query language’s flexibility and richness add complexity that may not be worth it for simple APIs.

GraphQL, despite its name, does not offer the same breadth of graph operations as a full-featured graph database like Neo4j or even SQL dialects that support transitive closure. A GraphQL interface reporting an individual’s parents, for example, cannot return the entire set of their ancestors in a single query.

GraphQL is a query language that facilitates interaction with APIs. It is a server-side runtime for APIs whose priority is to give clients the exact data they need and no more. GraphQL provides a complete description of data in a query and makes it easy to evolve APIs over time. 

GraphQL was designed to make APIs flexible, fast, and developer-friendly. You can also deploy it within an Integrated Development Environment (IDE) called GraphiQL. It provides an alternative to REST, allowing developers to create requests that can pull data from multiple data sources within a single API call. 

A type system, query language, and execution semantics, as well as static validation and type introspection, are all part of GraphQL. It allows for reading, writing (mutating), and subscribing to data changes (real-time updates, which are most commonly implemented using Websockets). Haskell, JavaScript, Perl, Python, Ruby, Java, C++, C#, Scala, Go, Rust, Elixir, Erlang, PHP, R, D, and Clojure are among the languages for which GraphQL servers are available.

GraphQL is used by API developers to create a schema that describes all of the data that clients can query through the service. Object types define which types of objects can be requested and what fields they have in a GraphQL schema.

GraphQL validates queries against the schema as they come in. The validated queries are then executed by GraphQL. Each field in a schema is assigned to a resolver by the API developer. The resolver is called during execution to produce the value.

serverless graphql: graphql working
Image Source

Key Benefits of GraphQL

  • Strong Typing: In GraphQL, all request and response fields should conform to a previously declared type. This eliminates a significant number of bugs.
  • Client-specific Interfaces: The client can specify the fields to be retrieved in the request and the server will only return those fields. 
  • Retrieving Multiple Data Levels in a Query: GraphQL makes it easy for you to request for a user, the posts for that user as well as the comments in just one query. GraphQL makes requests to a single endpoint. The operation to be performed or data to be returned is determined by the query specified by the user in the request. 
serverless graphql: benefits of graphql
Image Source

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

Building a Serverless GraphQL API Endpoint

You can now start to build the Serverless GraphQL API and then deploy it to AWS. 

Serverless GraphQL: Setup the Serverless Framework

  • First, let’s initialize the Node.JS project:
yarn init
  • Next, add the serverless configuration to the serverless.yml file:
service: serverless-api-sample # service name

provider:
  name: aws 
  runtime: nodejs12.x
  versionFunctions: false # no function versioning
  region: us-east-1 # The AWS region
  apiGateway:
    shouldStartNameWithService: true

functions:
  graphql:
    handler: src/graphql.handler # Path to lambda handler 
    events:
      - http:
          path: graphql # The lambda endpoint
          method: any # The lambda can be accessed by any HTTP method
          cors: true # enable CORS
  • You can now create a handler for the Lambda. Add the following code to src/graphql.js:
exports.handler = () => {
  console.log('An API')
}

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!

Serverless GraphQL: Test the Serverless Function

  • You can install the serverless-offline plugin and test your Lambda locally. Simply run the following command:
yarn add -D serverless-offline
  • Add this to the end of serverless.yml file:
plugins:
  - serverless-offline
  • To the package.json file, add the following script:
{
  ...
  "scripts": {
    "start": "sls offline"
  }
}
  • Finally, run the yarn start command and visit localhost:3000/dev/graphql on your web browser.

Serverless GraphQL: Setup a GraphQL Lambda in Apollo Server

  • The apollo-server-lambda provides a great way of building a serverless GraphQL API. To include it in your project, run the following command:
yarn add -D apollo-server-lambda
  • Add the following code to src/schema.graphql to define the  GraphQL schema:
type Query {
  item(id: ID!): Item
}

type Mutation {
  createItem(content: String!): Item
}

type Item {
  id: ID!
  content: String
}
  • In the above schema, you have defined an Item, which is an entity made of id and content. You have also defined a mutation named createItem to create an item from a content , plus a query item to get it from an id
  • Add the following to src/graphql.js:
const fs = require('fs')
const { ApolloServer, gql } = require('apollo-server-lambda')

// get GraphQL schema
const schema = fs.readFileSync('./src/schema.graphql', 'utf8')

// The resolver functions
const resolvers = { 
  Query: {
    item: () => {},
  },

  Mutation: {
    createItem: () => {},
  }
};

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

// start the server when Lambda is called
exports.handler = server.createHandler();
  • The code will create an Apollo server and then return a response, using the resolvers and the schema. You can test it by opening localhost:3000/dev/graphql. 
  • It should be working, but the resolvers are not doing anything. Take a look at how to use real data stored in a database. 

Serverless GraphQL: Use DynamoDB Data

  • It is easy to use the AWS DynamoDB with serverless.yml. To your current configuration, add the following code:
provider:
  ...
  environment:
    ITEM_TABLE: ${self:service}-items-${self:provider.stage} # table name
  iamRoleStatements:
    - Effect: Allow # permit Lambda to Get and Put Items into the table
      Action:
        - dynamodb:GetItem 
        - dynamodb:PutItem
      Resource: 'arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.ITEM_TABLE}'

resources:
  Resources:
    ItemsTable: # table definition
      Type: 'AWS::DynamoDB::Table'
      Properties:
        AttributeDefinitions:
          - AttributeName: itemId
            AttributeType: S
        KeySchema:
          - AttributeName: itemId
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:provider.environment.ITEM_TABLE}
  • The code asks serverless to create a table for items and give Lambda permissions to interact with the table. 
  • You can use aws-sdk to interact with the new DynamoDB table:
yarn add -D aws-sdk
  • It’s now time to update the resolvers. To make them more maintainable, store them in different files. The following is the new item query:
const AWS = require('aws-sdk')

async function item(_, { id }) {
  const dynamoDb = new AWS.DynamoDB.DocumentClient()

  const params = {
    TableName: process.env.ITEM_TABLE,
    Key: {
      itemId: id,
    },
  }

  const { Item } = await dynamoDb.get(params).promise()

  return {
    ...Item,
    id: Item.itemId,
  }
}
  • Then the new createItem mutation:
const AWS = require('aws-sdk')
const { v4 } = require('uuid')

async function createItem(_, { content }) {
  const dynamoDb = new AWS.DynamoDB.DocumentClient()
  const id = v4()

  const params = {
    TableName: process.env.ITEM_TABLE,
    Item: {
      itemId: id,
      content,
    },
  }

  await dynamoDb.put(params).promise()

  return {
    content,
    id,
  }
}
  • Now install the uuid and use it to create an id for new items
yarn add uuid
  • The serverless GraphQL API is now ready. You can deploy it to AWS. 

Serverless GraphQL: Deploy the Serverless GraphQL API to AWS

  • Run the following command to deploy the new Lambda to AWS:
serverless deploy

That is how to build a serverless GraphQL API endpoint. 

Conclusion

This article explains that APIs facilitate communication between systems. They can facilitate the transfer of data from one system to another and a server-based API architecture imposes an extra burden on the users, especially server maintenance. A serverless GraphQL API architecture on the other hand provides a fast, scalable, and reliable way of working with APIs. It relieves API users from server administration tasks to focus on code. 

visit our website to explore hevo

Hevo Data, a No-code Data Pipeline provides you with a consistent and reliable solution to manage data transfer between a variety of sources and a wide variety of Desired Destinations, with a few clicks. Hevo Data with its strong integration with 100+ sources (including 40+ free sources) allows you to not only export data from your desired data sources & load it to the destination of your choice, but also transform & enrich your data to make it analysis-ready so that you can focus on your key business needs and perform insightful analysis using BI tools.

Want to take Hevo for a spin?

Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand. You can also have a look at the unbeatable pricing that will help you choose the right plan for your business needs.

No-code Data Pipeline For Your Data Warehouse