The Power of Serverless GraphQL with AWS AppSync

Every story needs a hero. But, not all heroes are the same. Some of them have superpowers, and some are ordinary people. This story’s hero is just a regular software developer who works in a small team on a medium-size application. Our hero loves his job most of the time, except when he sends a test push notification to thousands of their customers in production, like a few minutes ago.

One day, his boss came with a new project. “We need to build a new complex application for our new important customer.” Nice, our hero loves challenges! “But we need to do it fast, as we have a short deadline because they have an important marketing event!” Ok, how fast do we need to build an app? “It needs to be ready for yesterday. And it needs to be real-time and scalable!”

The new project is a big challenge for our hero, as he never did that kind of project. Can he even do it?

“You can do it,” his boss says. “I also hired a famous consultant to help you.” That’s awesome! Challenge accepted.

After a full-day meeting with the consultant, and a whiteboard full of weird diagrams, the plan was simple: “Just use Kubernetes!”

But our hero doesn’t know Kubernetes. And there’s no time to learn it now. What should he do?

He started wondering if he is the only one who doesn’t know Kubernetes. Is he good enough for this job?

Our hero spent a sleepless night in front of his computer with his faithful sidekick, a rubber duck. He tried to learn as much as he can about this new technology. But he ended up more confused and tired.

You should try Serverless GraphQL

In the middle of the night, our hero’s faithful sidekick said, “you should try serverless GraphQL.”

Was he dreaming? And what the heck is serverless GraphQL? He knows what serverless is, but what’s GraphQL?

What’s GraphQL

Do you remember when Mark Zuckerberg said, “our biggest mistake was betting too much on HTML5?” It was a long time ago, back in 2012, when HTML5 was in its early days.

At that moment, the Facebook mobile app was an HTML5 web app embedded in the native mobile shell. They served all the news feed updates as HTML data from the server. However, HTML5 was in its early days, and the mobile web views were not performant enough, so the app wasn’t stable and scalable enough.

In 2012, Facebook’s engineering team started rebuilding their mobile and switching to the native iOS and Android apps. They evaluated different options for delivering the news feed data, including RESTful services and Facebook Query Language (FQL).

In the “GraphQL: A data query language” article in 2015, Lee Byron wrote:

We were frustrated with the differences between the data we wanted to use in our apps and the server queries they required. We don’t think of data in terms of resource URLs, secondary keys, or join tables; we think about it in terms of a graph of objects and the models we ultimately use in our apps like NSObjects or JSON.

This frustration led the Facebook engineering team to rethink the way they serve data to their mobile application. Instead of returning a full model with a lot of unnecessary data, they tried to develop a new system to return only the data the application needed.

In 2015, they announced GraphQL, an open-source data query language. The idea behind GraphQL was simple, the client defines the data structure, and the server provides a JSON response with precisely the same format.

For example, the client wants to get the user with a specified ID. However, the application needs only the user’s name, a profile photo with a specific size, and the first five friend connections. Instead of sending two or three different requests to the RESTful API, with GraphQL, you can send a request similar to the one in the image below. And the response will be the JSON with the same structure, as you can see on the right side of the same image.

That sounds nice and smart. But why should our hero care about GraphQL? He doesn’t have the same problem Facebook had.

The problem Facebook’s engineering team had was the leading cause for inventing GraphQL. However, that’s not the only problem GraphQL solves. If you have one of the following symptoms, GraphQL might be the cure for the problems your application faces, too:

  • Distinct front end clients for multiple platforms, such as web and mobile, have different data requirements.
  • Your back end serves data to your client apps from different sources. For example, your app has SQL and NoSQL databases, and it connects to some external systems.
  • Your app has a complex state and caching managements for both front end and back end.
  • Slow pages, especially on mobile, caused by multiple dependant HTTP requests.

This list is not complete, and GraphQL can bring even more benefits to your application. Some of the main characteristics of GraphQL are:

  • It defines a data shape. The request always specifies the response’s form, which makes requests more predictable and easier to use.
  • It’s hierarchical. Its strict relation between objects with graph-structured data simplifies getting data from multiple sources.
  • It’s strongly typed. It can give you descriptive error messages before you run a query.
  • It’s a protocol, not storage. Each GraphQL field is backed by a function on the back end, which allows you to connect it to any storage you want in the background.
  • It’s introspective. You can query the GraphQL server for the types it supports. This gives you built-in documentation and also a base for a powerful toolset.
  • It’s version free. The shape of the data is always defined by the client’s request, which means adding additional fields to your model will not affect your client application until you change the query itself.

To combine data from multiple sources using RESTful API, you often send multiple HTTP requests and then connect data on the client-side. This works fine in perfect conditions. However, users don’t always use your app in ideal conditions. They are often on mobile with a limited or unstable network. Or they live in Australia, and each request is a few hundred milliseconds slower.

With GraphQL, you can archive the same with a single request. This will push a bit more load to the server-side, but that works just fine in most cases. It’s even better when you don’t own the server.

#serverless #aws #cloud #developer #graphql

What is GEEK

Buddha Community

The Power of Serverless GraphQL with AWS AppSync
Christa  Stehr

Christa Stehr

1598408880

How To Unite AWS KMS with Serverless Application Model (SAM)

The Basics

AWS KMS is a Key Management Service that let you create Cryptographic keys that you can use to encrypt and decrypt data and also other keys. You can read more about it here.

Important points about Keys

Please note that the customer master keys(CMK) generated can only be used to encrypt small amount of data like passwords, RSA key. You can use AWS KMS CMKs to generate, encrypt, and decrypt data keys. However, AWS KMS does not store, manage, or track your data keys, or perform cryptographic operations with data keys.

You must use and manage data keys outside of AWS KMS. KMS API uses AWS KMS CMK in the encryption operations and they cannot accept more than 4 KB (4096 bytes) of data. To encrypt application data, use the server-side encryption features of an AWS service, or a client-side encryption library, such as the AWS Encryption SDK or the Amazon S3 encryption client.

Scenario

We want to create signup and login forms for a website.

Passwords should be encrypted and stored in DynamoDB database.

What do we need?

  1. KMS key to encrypt and decrypt data
  2. DynamoDB table to store password.
  3. Lambda functions & APIs to process Login and Sign up forms.
  4. Sign up/ Login forms in HTML.

Lets Implement it as Serverless Application Model (SAM)!

Lets first create the Key that we will use to encrypt and decrypt password.

KmsKey:
    Type: AWS::KMS::Key
    Properties: 
      Description: CMK for encrypting and decrypting
      KeyPolicy:
        Version: '2012-10-17'
        Id: key-default-1
        Statement:
        - Sid: Enable IAM User Permissions
          Effect: Allow
          Principal:
            AWS: !Sub arn:aws:iam::${AWS::AccountId}:root
          Action: kms:*
          Resource: '*'
        - Sid: Allow administration of the key
          Effect: Allow
          Principal:
            AWS: !Sub arn:aws:iam::${AWS::AccountId}:user/${KeyAdmin}
          Action:
          - kms:Create*
          - kms:Describe*
          - kms:Enable*
          - kms:List*
          - kms:Put*
          - kms:Update*
          - kms:Revoke*
          - kms:Disable*
          - kms:Get*
          - kms:Delete*
          - kms:ScheduleKeyDeletion
          - kms:CancelKeyDeletion
          Resource: '*'
        - Sid: Allow use of the key
          Effect: Allow
          Principal:
            AWS: !Sub arn:aws:iam::${AWS::AccountId}:user/${KeyUser}
          Action:
          - kms:DescribeKey
          - kms:Encrypt
          - kms:Decrypt
          - kms:ReEncrypt*
          - kms:GenerateDataKey
          - kms:GenerateDataKeyWithoutPlaintext
          Resource: '*'

The important thing in above snippet is the KeyPolicy. KMS requires a Key Administrator and Key User. As a best practice your Key Administrator and Key User should be 2 separate user in your Organisation. We are allowing all permissions to the root users.

So if your key Administrator leaves the organisation, the root user will be able to delete this key. As you can see **KeyAdmin **can manage the key but not use it and KeyUser can only use the key. ${KeyAdmin} and **${KeyUser} **are parameters in the SAM template.

You would be asked to provide values for these parameters during SAM Deploy.

#aws #serverless #aws-sam #aws-key-management-service #aws-certification #aws-api-gateway #tutorial-for-beginners #aws-blogs

Fredy  Larson

Fredy Larson

1599105420

AWS AppSync: Conditional Resolvers Using the Info Context

AWS AppSync

AppSync is a managed GraphQL service offered by Amazon Web Services and can be used to build scalable enterprise APIs. A typical AppSync solution consists of small resolvers that can be combined to access various data sources such as databases, HTTP APIs or AWS Lambda.


Introduction

In this example, I will be talking about using AWS AppSync with AWS Lambda data sources and one of the challenges I have come across while developing enterprise scale solutions with these technologies.

Each Lambda resolver you have in a particular request triggers an invocation. The problem comes with having nested resolvers where you only request data from the nested Lambda rather than the parent Lambda. As a result you will cause several invocations, incur cost and resource for the first Lambda without needing to.

If you’re running enterprise serverless it is important to consider the architecture to reduce the amount of compute where possible and lower the risk of hitting limits imposed by AWS.

Thankfully, AWS released an AppSync update in Feb 2020 giving us access to the context info object so we can mitigate this issue. Read more here.

Let’s dive in! 💥

Say you have a GraphQL endpoint and schema to retrieve a typical blog post:

type Post{
  id: ID!
  title: String!
  content: String!
  image: ImageData!
}
type ImageData{
  id: ID!
  postId: ID!
  path: String!
  tags: String
}
type Query{
  getPost(id: ID!): Post!
}

Using GraphQL, your query could look like:

query GetPost{
  getPost(id: $id){
    title
    content
    image{
      path
      tags
    }
  }
}

#aws-appsync #graphql #aws-lambda #serverless #aws

Chaz  Homenick

Chaz Homenick

1596762420

Effective Direct Lambdas for AWS AppSync (Spoiler: They Are Really Effective)

Today, I’m going to walk you through using AppSync’s Direct Lambda feature. I built the thing during my internship this Summer after all, so I should be able to express how simple, yet effective, this feature is in allowing you to configure Lambdas for your API on AppSync.

_Go ahead and jump to the section labelled __Let there be an API! _if you’d like to skip the bits about what the old workflow for a Lambda resolver was like.

I’d first like to make a point about why Direct Lambdas were necessary. Here’s a picture to help demonstrate that point.

Image for post

VTL? Cancelled, sorta. Call the mob.

In order to set up a Lambda resolver for a field on AppSync, you’d first have to check out the resolver mapping template reference, then you’d have to set up your mapping templates in a language called VTL. These templates translate data back and forth between your Lambda. Finally, you’d be able to set up your Lambda to expect the data as translated by the mapping templates.

Notice that I mentioned that you had to write code in two separate places: the Lambda and the mapping templates, which might be in the Appsync console editors, uploaded through the SDK, or in a CloudFormation template. This introduces unnecessary coupling between your Lambda code and your mapping templates, which is probably not optimal for your code-base, nor your mental health.

This is where the problem lies: if it’s at all complicated, then it’s too complicated. The goal is to think less… Er, less about things that don’t matter, that is.

If only there was an easier way to configure a Lambda resolver on AppSync. If only there was a way to write less code and get more done.

There is now a way, Direct Lambdas.

Image for post

This is probably how things work under the hood.

Let there be an API!

I’d like to avoid making this tutorial dry and boring so I’ve decided that our API will be all about awesome, original, definitely-not-cringe dad jokes! Plus, we can utilize a friendly API called icanhazdadjokes that offers an unprecedented collection of definitely-not-cringe-worthy dad jokes for free. That’s a low price!

Let’s start off with a specification of what our API should do. I’d like to create an API that will allows a client to either get a random Joke or get a Joke specified by an ID.

What makes up a Joke?

  • joke: The content of the joke
  • id: The id of the joke
  • imageUrl: A permalink to the joke
  • cringe: A boolean that shows if the joke is cringe or not

Here’s how the entire thing will work:

Image for post

#aws #graphql #serverless #aws-lambda #aws-appsync

Lindsey  Koepp

Lindsey Koepp

1594688114

AWS Amplify and GraphQL— an Introduction

Amplify is a product from AWS that has two aspects to it:

  • Amplify framework which as an open-source framework which provides a CLIlibraries to integrate frontend code with the backend and UI components to build fullstack iOS, Android, Web, and React Native apps. You can configure and integrate the underlying cloud services like AWS AppSync (Managed GraphQL, offline data sync), Amazon Cognito (Authentication, Authorization, User Management, MFA), Amazon Pinpoint (Analytics, Customer Engagement), AWS Lambda (GraphQL Resolver, Business logic), Amazon S3 (Storage), or Amazon Lex (Conversation Bots) directly from your command line minimizing the time required to set-up and manage your back-end services.
  • The Amplify Console provides a Git-based workflow for hostingfullstack serverless web apps with continuous deployment.

Image for post

It also supports static-site generators like **Gatsby, Eleventy, Hugo, VuePress, **and Jekyll. You can deploy serverless backends with GraphQL/REST APIsauthenticationanalytics, and storage created by the Amplify CLI on the same commit as your frontend code.

Important: You can use Amplify console to deploy and host Single Page App (SPA) frontends and static websites, without using the Amplify Framework.

GraphQL

Amplify supports GraphQL, which is yet another API technology just like REST, SOAP, gRPC, Thrift, OpenAPI (Swagger) etc. First of all, GraphQL is not a Graph database query language. GraphQL is a query language for your APIs which offers a strong type system, great tools for **domain modelling **and many other features.

Components

  • **Schema — **Each GraphQL API is defined by a single GraphQL schema. A GraphQL server’s type system is referred to as that server’s schema. All data operations are validated against this schema. GraphQL comes with a set of default scalar types out of the box (Int, Float, String, Boolean, ID), allows you to create own scalar / object types and supports interfacesunion and list types.
  • **Data Source — **This is the source of the data for the GraphQL API. The data source could be of any type, as long as one is authorized to read from it.
  • Resolvers — Resolvers are the components that connect with the data source and are able to map a schema with it.

Note: GraphQL isn’t tied to any specific database or storage engine and is instead backed by your existing code and data.

In GraphQL, you define certain types as part of domain modelling which are part of your schema. In the following image, the “!” at the end of the type means that the field is required or Not-Null.

#graphql #full-stack #aws-amplify #serverless #aws #graphql

The Power of Serverless GraphQL with AWS AppSync

Every story needs a hero. But, not all heroes are the same. Some of them have superpowers, and some are ordinary people. This story’s hero is just a regular software developer who works in a small team on a medium-size application. Our hero loves his job most of the time, except when he sends a test push notification to thousands of their customers in production, like a few minutes ago.

One day, his boss came with a new project. “We need to build a new complex application for our new important customer.” Nice, our hero loves challenges! “But we need to do it fast, as we have a short deadline because they have an important marketing event!” Ok, how fast do we need to build an app? “It needs to be ready for yesterday. And it needs to be real-time and scalable!”

The new project is a big challenge for our hero, as he never did that kind of project. Can he even do it?

“You can do it,” his boss says. “I also hired a famous consultant to help you.” That’s awesome! Challenge accepted.

After a full-day meeting with the consultant, and a whiteboard full of weird diagrams, the plan was simple: “Just use Kubernetes!”

But our hero doesn’t know Kubernetes. And there’s no time to learn it now. What should he do?

He started wondering if he is the only one who doesn’t know Kubernetes. Is he good enough for this job?

Our hero spent a sleepless night in front of his computer with his faithful sidekick, a rubber duck. He tried to learn as much as he can about this new technology. But he ended up more confused and tired.

You should try Serverless GraphQL

In the middle of the night, our hero’s faithful sidekick said, “you should try serverless GraphQL.”

Was he dreaming? And what the heck is serverless GraphQL? He knows what serverless is, but what’s GraphQL?

What’s GraphQL

Do you remember when Mark Zuckerberg said, “our biggest mistake was betting too much on HTML5?” It was a long time ago, back in 2012, when HTML5 was in its early days.

At that moment, the Facebook mobile app was an HTML5 web app embedded in the native mobile shell. They served all the news feed updates as HTML data from the server. However, HTML5 was in its early days, and the mobile web views were not performant enough, so the app wasn’t stable and scalable enough.

In 2012, Facebook’s engineering team started rebuilding their mobile and switching to the native iOS and Android apps. They evaluated different options for delivering the news feed data, including RESTful services and Facebook Query Language (FQL).

In the “GraphQL: A data query language” article in 2015, Lee Byron wrote:

We were frustrated with the differences between the data we wanted to use in our apps and the server queries they required. We don’t think of data in terms of resource URLs, secondary keys, or join tables; we think about it in terms of a graph of objects and the models we ultimately use in our apps like NSObjects or JSON.

This frustration led the Facebook engineering team to rethink the way they serve data to their mobile application. Instead of returning a full model with a lot of unnecessary data, they tried to develop a new system to return only the data the application needed.

In 2015, they announced GraphQL, an open-source data query language. The idea behind GraphQL was simple, the client defines the data structure, and the server provides a JSON response with precisely the same format.

For example, the client wants to get the user with a specified ID. However, the application needs only the user’s name, a profile photo with a specific size, and the first five friend connections. Instead of sending two or three different requests to the RESTful API, with GraphQL, you can send a request similar to the one in the image below. And the response will be the JSON with the same structure, as you can see on the right side of the same image.

That sounds nice and smart. But why should our hero care about GraphQL? He doesn’t have the same problem Facebook had.

The problem Facebook’s engineering team had was the leading cause for inventing GraphQL. However, that’s not the only problem GraphQL solves. If you have one of the following symptoms, GraphQL might be the cure for the problems your application faces, too:

  • Distinct front end clients for multiple platforms, such as web and mobile, have different data requirements.
  • Your back end serves data to your client apps from different sources. For example, your app has SQL and NoSQL databases, and it connects to some external systems.
  • Your app has a complex state and caching managements for both front end and back end.
  • Slow pages, especially on mobile, caused by multiple dependant HTTP requests.

This list is not complete, and GraphQL can bring even more benefits to your application. Some of the main characteristics of GraphQL are:

  • It defines a data shape. The request always specifies the response’s form, which makes requests more predictable and easier to use.
  • It’s hierarchical. Its strict relation between objects with graph-structured data simplifies getting data from multiple sources.
  • It’s strongly typed. It can give you descriptive error messages before you run a query.
  • It’s a protocol, not storage. Each GraphQL field is backed by a function on the back end, which allows you to connect it to any storage you want in the background.
  • It’s introspective. You can query the GraphQL server for the types it supports. This gives you built-in documentation and also a base for a powerful toolset.
  • It’s version free. The shape of the data is always defined by the client’s request, which means adding additional fields to your model will not affect your client application until you change the query itself.

To combine data from multiple sources using RESTful API, you often send multiple HTTP requests and then connect data on the client-side. This works fine in perfect conditions. However, users don’t always use your app in ideal conditions. They are often on mobile with a limited or unstable network. Or they live in Australia, and each request is a few hundred milliseconds slower.

With GraphQL, you can archive the same with a single request. This will push a bit more load to the server-side, but that works just fine in most cases. It’s even better when you don’t own the server.

#serverless #aws #cloud #developer #graphql