Hills 🏔 and Skills, What's Common?

They both need you to be on top.

Cohort-1 just ended. You will get:

All yours, just at:

$99

AWS AppSync vs API Gateway - A Comprehensive Guide in 2023

Updated on
appsync vs apigw banner

Developers are awesome. You have miles to go, and APIs to build. You have to create different kinds of APIs - REST, HTTP, GraphQL and even Web Sockets!

AWS solves these very issues by providing serverless, managed API services that fit the developer of the ever-changing needs, and to make their life a lot easier.

With serverless, you only pay for just what you use. Your usage is determined by the number of requests and payload size of each request sent.

i love rest meme

What is AppSync? Not a syncing service.

AppSync is an AWS managed GraphQL service. Hold on. I know what you might be thinking ….

It must be so hard and complicated, at the end it’s just GraphQL?

Not with AppSync. It helps you with the hard bits.

You can easily create GraphQL APIs by directly writing mapping templates in JavaScript or VTL. Directly connect it to other AWS services like DynamoDB, RDS, HTTP Endpoint, Lambda, OpenSearch, EventBridge.

What is API Gateway? Asking for a friend.

API Gateway is a fully managed serverless AWS API service, which allows you to create REST, HTTP, and Web Socket APIs.

You define the routes, schema, methods and simply attach it to your Lambda function.

Now your Lambda is responsible to parse, validate and query the database.

There are several runtimes available for you to write your Lambda code: NodeJS, Python, Go, Java and .NET.

You pay for the API Gateway and your Lambda function, more on that later.

api gateway expressjs meme

What is GraphQL? Asking for myself.

It is a query language, but for APIs. It enables you to save the world (literally) by:

thus saving battery life and CPU cycles: Which otherwise would be forfeited to request-hungry apps.

Queries are used to fetch data, almost analogous to GET in REST, but just that every GraphQL request is internally POST.

Mutations are what you use when you want to PUT, POST, PATCH or DELETE, but in GraphQL.

Show me the code. Enough talking.

Here you go:

An example of GraphQL Query which fetches the cat breeds with name, description, lifespan and photos.

query {
  breed(id: "ragdoll") {
    name
    description
    lifespan
    photos {
      thumbnail
      fullres
    }
  }
}

Now this is the response which you will get.

No more, No less. Just what you asked for.

{
  "data": {
    "breed": {
      "name": "Ragdoll",
      "description": "Description: Blue eyes, colorpoint coat, semilong hair",
      "lifespan": "12 - 17 years",
      "photos": [
        {
          "thumbnail": "https://cdn2.thecatapi.com/images/25b.jpg",
          "fullres": "https://cdn2.thecatapi.com/images/26b.jpg"
        },
	      {
          "thumbnail": "https://cdn2.thecatapi.com/images/15b.jpg",
          "fullres": "https://cdn2.thecatapi.com/images/16b.jpg"
        },
      ]
    }
  }
}

I know the JSON is a bit data-heavy.

Here, enjoy this visual graph ^_^

graphql graph diagram

In GraphQL, schema validation is built-in unlike HTTP.

This means you are protected against sending any wrong data in the request. For example, you have defined your cat’s age as an integer in the schema. And that’s exactly how it should be.

By mistake if you were to send a request with your cat’s breed as 1234 (an integer) instead of the id (a string), the request won’t go through.

GraphQL Subscriptions

Get Real-time updates without building Web Socket APIs. You now know about the usual queries and mutations. What is a subscription?

GraphQL subscriptions are a tad bit different. It uses Web Sockets internally to listen for the events. They enable you to publish updates to data in real time to clients who are subscribed to you.

When a mutation occurs or data is changed — Subscribed clients would be automatically notified.

It follows a publish-subscribe (pub/sub) method.

You can send a message using mutations and your subscriber will receive it. Without invoking any Lambda function.

REST vs GraphQL

In REST we can make different types of requests: GET · POST · PUT · PATCH · DELETE · OPTIONS

In GraphQL we can make the same requests using: Query · Mutation · Subscription.

They both use the same protocol — HTTP / HTTPS. GraphQL only uses the POST method to send and receive JSON.

Which API is right for you? You’ll find out today after reading this blog.

Let’s consider a real-life scenario.

Suppose: You have a client named Becky, who breeds cats for a living. And you breed websites for a living. Just kidding. She wishes to create a website showcasing the cat family, and wants to sell cats.

These are the things which might happen:

cute kittens

I’ll show you a comparison with a Cat CRUD API:

OperationRESTGraphQL
Add a catPOST /catmutation addCat()
Get a catGET /cat/:idquery getCat()
Update a catPATCH /cat/:idmutation patchCat()
List catsGET /catsquery listCats()
Delete a catDELETE /cat/:idmutation deleteCat()

The Best Ways to Create API

We have chalked out the APIs you need to create for Becky’s cats. Now we need to actually create this somewhere.

Using API Gateway

These are the steps you need to take in order to get the Cat API to work:

  1. Create an API which can be HTTP or REST.
  2. Create a Lambda function written in JavaScript, Python (any supported language).
  3. Use the AWS DynamoDB SDK to insert, retrieve, delete or update the cats.

Sounds simple? But is it simple to implement?

You’re right. It’s not.

You’ll be creating five Lambdas: Where you’ll be parsing the request with JSON.parse() and again you’ll stringify them.

Although you can directly write the mapping template for DynamoDB in REST API, it won’t give you much flexibility. Eg: Generating a unique ID for your cat.

Using AppSync

GraphQL itself might seem hard. But it does get easier.

Only with AppSync, you can create APIs within minutes that will scale.

This is how you GraphQL APIs with AppSync in four simple steps.

  1. Define the GraphQL schema. It will look like this:

    enum Color {
    	WHITE
    	BROWN
    	ORANGE
    	BLACK
    	GREY
    }
    
    input CatInput {
    	name: String!
    	age: Int!
    	color: Color!
    	photo: String
    }
    
    type CatOutput {
    	name: String
    	age: Int
    	color: Color
    	photo: String
    }
    
    type Query {
    	getCat(id: ID!): CatOutput
    	listCat: [CatOutput]
    }
    
    type Mutation{
    	addCat(input: CatInput!): CatOutput
    	updateCat(input: CatInput!): CatOutput
    	deleteCat(id: ID!): CatOutput
    }
    
    schema {
    	query: Query,
    	mutation: Mutation
    }
  2. Create data source (eg: DynamoDB, RDS, HTTP(S), Lambda) You can connect to DynamoDB as your preferred data source.

  3. Create resolvers (request and response mapping templates)

    • DynamoDB example to add a new cat’s details with JavaScript:

      import { util } from "@aws-appsync/utils";
      
      export function request(ctx) {
        const id = util.autoKsuid();
      
        const item = {
          PK: `CAT#${id}`,
          SK: `CAT#${id}`,
          GSI1PK: "CATS#",
          GSI1SK: `CAT#${id}`,
          ...ctx.args.input,
        };
      
        return {
          operation: "PutItem",
          item: ctx.util.dynamodb.toDynamoDB(item),
        };
      }
      
      export function response(ctx) {
        if (ctx.error) {
          ctx.util.error("Error adding the cat.", "Error", null, ctx.error);
        }
        return ctx.result.item;
      }
    • RDS example with VTL:

      {
          "version": "2018-05-29",
          "statements": [
              "insert into CATS VALUES (:ID, :NAME, :AGE, :COLOR, :PHOTO)"
          ],
          "variableMap": {
              ":NAME": $util.toJson($ctx.args.input.name),
              ":AGE": $util.toJson($ctx.args.input.age),
              ":COLOR": $util.toJson($ctx.args.input.color)
              ":PHOTO": $util.toJson($ctx.args.input.photo)
          }
      }
      
  4. Connect resolvers to your data source like DynamoDB or RDS

API Gateway

API Gateway allows you to create REST APIs which are HTTP-based. The standard HTTP methods we can implement are GET, POST, PUT, PATCH, and DELETE.

It can also help us to create WebSocket APIs that enable full-duplex communication between client and server. Fascinatingly, it has the ability to route specific incoming messages based on the content of the message.

Aren’t REST and HTTP APIs the same?

Not really.

Although both REST APIs and HTTP APIs are RESTful — REST APIs are more feature-rich compared to HTTP APIs.

You get:

In REST, you can directly connect to DynamoDB or HTTP API, but you will not get the features of VTL or JavaScript (example: map, filter, if-else).

HTTP APIs aren’t to be left out in the cold either.

They are designed for your next minimalist project. Features that hit the nail on the head.

They are optimized for serverless workloads and HTTP backends. HTTP APIs support OpenID Connect and OAuth 2.0 authorization, with built-in support for CORS and automatic deployments.

And prices? Always lower than the ‘REST’.

For example, you can create an HTTP API that integrates with a Lambda function on the backend. When Becky calls your Cat API, API Gateway sends the request to the Lambda function and returns the function’s response to Becky.

Web Socket APIs — The Cool Sibling

Imagine you could talk to your friend, but

Sounds like pigeon-mail?

You’ll just want to converse over a phone. It’s real-time. Allows a two-way communication.

Web Socket APIs are no different. For applications which need chat or streaming real-time data dashboards like finance values, you need to use the Web Socket API.

It enables a richer client / service interaction. You don’t need to keep sending explicit requests like in REST or HTTP.

‘REST Assured’ Integrations — As Simple as Pie

We can connect Amazon DynamoDB directly to a REST API in Amazon API Gateway. The API Gateway provides you with seamless integration with other AWS services such as Lambda.

You’ll just need to

You could create a POST method in your REST API that integrates with DynamoDB to put your cats’ details into a table called Cat. It would send the request data to DynamoDB and create your furry new cat records in the table.

Mapping templates in REST API

Yes, you can directly perform DynamoDB CRUD Operations in API Gateway using VTL (Velocity Template Language).

It takes parameters and values for the table name and fields.

In this mapping template, the S and N indicate that the id and name are string types and age is a number type in DynamoDB.

  1. Create (Put Item)

    For a POST request to create a new item in the Cat table:

    {
    	"TableName": "Cat",
    	"Item": {
    		"id": {
    			"S": "$input.path('$.id')"
    		},
    		"name": {
    			"S": "$input.path('$.name')"
    		},
    		"age": {
    			"N": "$input.path('$.age')"
    		},
    		"color": {
    			"S": "$input.path('$.color')"
    		},
    		"photo": {
    			"S": "$input.path('$.photo')"
    		}
    	}
    }

    It requires a request body in a JSON object with the defined fields id, name, age, color and photo fields.

    {
    	"id": "1",
    	"name": "Fluffy",
    	"age": "2",
    	"color": "GREY",
    	"photo": "/path/to/cat.jpg"
    }

Use Cases: The Litmus test for AppSync vs API Gateway

Using AWS is all about owning your flexibility. It’s about managing your project by choosing the right tools for the right occasion. At the end — It boils down to answering a simple questionnaire to see who’s actually the right fit.

Feature comparison table:

Here are the major ones you should ever need to think ‘bout.

Use CaseAPI GatewayAppSync
Managing traditional REST APIs?YesNo
Dealing with GraphQL APIs?NoYes
Real-time updates with subscriptions or websocket?YesYes
Handling offline users?NoYes
Aggregating data from different sources?NoYes
Securing your APIs with AWS IAM and Amazon Cognito?YesYes
Efficiency with caching?YesYes

A table of Yays and Nays. You can answer by ticking off one out of each block. Whichever side secures the more ticks — wins for you.

Learning Curve - Easy or Not?

No one is born talented with Lambda and VTL skills. Here is the table for you to make some decision:

ServiceDifficultyAPI Development Time
API Gateway with Lambda🟧 Moderate🟥 Most
AppSync with JavaScript🟩 Easy🟩 Least
AppSync with Lambda🟧 Moderate🟧 Average
AppSync with VTL🟥 Hard🟧 Average

Pricing - Bang for your buck

Using HTTP API with AWS Lambda is cheaper than just using AppSync API.

Do note that you don’t get any of the GraphQL features in HTTP or REST API.

Performance - It depends…

Lambda suffers from cold start syndrome — No matter whether you use API Gateway or AppSync.

NOTE: Using Lambda with AppSync is optional

lambda invocation diagram

Now it’s up to you to design your API and DB implementation to get the best results. Example: If you are querying your database 5 times to serve a single request, it’ll take more time.

Do you want more?

This was just an introduction. Reading blogs will only take you so far.

Implementation can be tedious if you don’t know how to connect services altogether. LearnAWS masterclass teaches you to build APIs using CDK from scratch with best practices. It’s the only AWS course on the internet which does that.

Don’t think of clicking that JOIN button unless you want to be the best AWS developer.