Serverless GraphQL API with AWS Amplify AppSync and Cognito Auth

happy devSecOps

(λx.x)eranga
Effectz.AI
7 min readJul 22, 2022

--

Background

In my previous post I have discussed about building Serverless application with AWS Amplify, AWS API Gateway, AWS Lambda and Cognito Auth. In this post I’m gonna discuss about building Serverless GraphQL API with AWS Amplify. All the source codes which related to this post available in gitlab. Please clone the repo and continue the post.

AWS Amplify and GraphQL

GraphQL is a different way to connect client applications to the backend. Unlike REST, GraphQL has some important characteristics. Between the client and the server, a contract is signed, called the GraphQL schema. Here, all possible types of operations that the client can perform on the backend are defined. The client can call an operation with one request, which will return multiple types if needed so that there is no under fetch of information. The client can also specify attributes for the types it wants so that there is no over fetch of information. GraphQL is implemented between the client and the data sources, making GraphQL a single entry point to the backend. The data sources can be anything from NoSQL databases, relational databases, and HTTP servers to whatever returns data. To connect a GraphQL implementation to the data sources, you need to write resolvers. Resolvers are a very important part of your GraphQL application, as they are the ones that translate GraphQL requests or responses to whatever the data sources understand. For example, if the data source is a relational database, the resolver will need to know how to transform a GraphQL query into a SELECT operation and then translate whatever the relational database returns into a GraphQl response.

AWS Amplify announces the GraphQL Transformer version 2, enabling developers to develop more feature-rich, flexible, and extensible GraphQL-based app backends even with minimal cloud expertise. it can allow you to write a GraphQL schema, have the backend resolvers and database generated automatically, plus host everything on AWS, and a lot more. The AWS Amplify CLI is a command line toolchain that helps frontend developers create app backends in the cloud. With the Transformer, developers can configure their backend data model using the GraphQL Schema Definition Language, and Amplify CLI automatically transforms the schema into a fully functioning GraphQL API with its underlying cloud infrastructure.

AWS AppSync and GraphQL

AWS AppSync is a serverless GraphQL and Pub/Sub API service that simplifies building modern web and mobile applications. AWS AppSync GraphQL APIs simplify application development by providing a single endpoint to securely query or update data from multiple databases, microservices, and APIs. It can identify as the GraphQL serverside API and can be connected to AWS Identity and Access Management (IAM) for authenticated API requests. With AppSync developer simply defines their model in the form of a GraphQL schema, and automatically has a deployed GraphQL API with prebuilt templates for resolving to a database, such as DynamoDB.

AppSync can do everything GraphQL specifies and also has additional features that come out of the box. For example, it supports authentication and authorization. This enables to filter the data you return and the operations that the clients can perform, depending on which user is in. AppSync supports Cognito, API Key, IAM permissions, and Open ID Connect and even provides out-of-the-box support for DynamoDB, AWS Lambda, Elasticsearch, HTTP, and RDS as data sources.

Scenario

In this scenario I’m building simple GraphQL API to serve the Document model. The architecture of the application described in the Following Figure. It consists with different AWS services AWS AppSync, GraphQL Resolver, Cognito User Pool and DynamoDB. Authentication of the GraphQL API handles with AWS Cognito User Pool.

Following are the main steps that I have followed to develop the GraphQL API with AWS Amplify.

1. Setup Amplify Project

First I have installed and configured the Amplify. Then created react frontend app and enabled Cognito auth in the project. In my previous post I have discussed detailed information about this steps. Please follow that post and setup the Amplify project first.

2. Create GraphQL API

Then I have created GraphQL API. When creating API with Amplify it asks the API type, select GraphQL as the API type. I have given the name of the API as rahasakgraphqlapi and chosen the authorization type of the API Amazon Cognito User Pool. Finally need to select the GraphQL schema template. I have selected the Single object with fields (e.g., “Todo” with ID, name, description) option. Then it will create a GraphQL schema for Todo model in the amplify/backend/api/rahasakgraphqlapi/schema.graphql file. The Amplify backend configurations of the API defined in the amplify/backend/backend-config.json file.

3. Define GraphQL Schema

The default schema is created for the Todo model. I have renamed the Todo model schema with the Document and added the Document model information as below.

4. Define Access Control

Now that we have the base schema defined, we can move into defining our access controls. To do this we’ll be using the auth directive (@auth). The auth directive accepts an array of rules, each rule being an object. So, to start out, let's define the auth directive on the Document model. In this scenario I have given the permission for object owner to create, update, delete, read. by default, Amplify will add an owner field to our model if we don’t explicitly define an owner field or a way to track owners. Read more about GraphQL Auth from here.

5. Deploy GraphQL API

I can deploy the GraphQL API with the amplify push. When deploying it will create GraphQL queries, mutations and subscriptions related to the Document model. The generated queries, mutations, subscriptions and full schema of the GraphQL API can be found in the /src/graphql directory.

Once deployment completed, I will have a GraphQL server hosted on AWS, the remote endpoint address will be shown in the terminal. I can go into the AWS dashboard AWS AppSync and see exactly how much work Amplify has done in getting the backend set up.

6. Test GraphQL API From AWS AppSync

The created GraphQL APIs can be tested in the AWS AppSync dashboard. Different queries can be executed in the Queries window. To test the APIs I need to first Log In with Cognito User Pool user record credentials since auth is enabled in the GraphQL API. In previous post I have registered a user with username rahasaklabs in the Cognito User Pool. I have Log in with that users’ credentials here.

Once Log in I have created a Document object with GraphQL mutation API as below. In here I have specified the Document object parameters. When Document is created the API will returns the id of the created Document.

Created Document objects can be searched with query API. Following is the listDocuments query to get all available Document objects.

Following is the getDocument query to search the Document object with specific Document id.

7. Call GraphQL API From Frontend Web

Finally I have integrated the GraphQL API functions through the React frontend web. Once Sing In, it will shows Create Document button and List Documents button. When click on Create Document button it will send request to the GraphQL createDocument API. When click on List Documents button it will send request to the GraphQL listDocuments API. Please note that, to access these APIs, I need first Log In to the frontend app with the Cognito User Pool users’ credentials.

Reference

  1. https://epsagon.com/development/beginners-guide-to-aws-appsync/
  2. https://dev.to/codebeast/an-in-depth-guide-on-amplify-graphql-api-authorization-14ng
  3. https://acloudguru.com/blog/engineering/8-steps-to-building-your-own-serverless-graphql-api-using-aws-amplify
  4. https://rangle.io/blog/creating-a-useful-graphql-server-using-aws-amplify/
  5. https://dev.to/aws-builders/use-lambda-resolvers-in-your-graphql-api-with-aws-amplify-5e13
  6. https://aws.amazon.com/blogs/mobile/aws-appsync-offline-reference-architecture/
  7. https://iamondemand.com/blog/6-graphql-authorization-schemas-for-aws-amplify/
  8. https://www.kushki.com/en/blog/crea-tu-primera-api-graphql-con-aws-appsync
  9. https://blog.logrocket.com/multi-tenant-amplify-app-react-frontend/
  10. https://medium.com/@dantasfiles/multi-tenant-aws-amplify-cc3252c4def4

--

--