Part 2: AppSync Backend: AWS Managed GraphQL Service AWS AppSync architecture : : AppSync Backend: Managed GraphQL Service (this post) : : (Latest!!!) Part 1 Introduction: GraphQL endpoints with API Gateway + AWS Lambda Part 2 AWS Part 3 AppSync Frontend: AWS Managed GraphQL Service Part 4 Serverless AppSync Plugin: New Features “Powering your GraphQL endpoint with a serverless backend solves scaling and availability concerns outright, and it gives you a big leg up on security. It’s not even that much code or configuration”. - Part 1 Introduction In this part of the series, we will learn how to build endpoints with new AWS service called — . I will be creating a backend for a using AppSync with DynamoDB, ElasticSearch, and AWS Lambda integrations and show you how to configure and deploy AppSync using GraphQL AppSync launched at the re: Invent 2017 mini Twitter App new Serverless-AppSync-Plugin . Let’s get started! 🏃 Note: If you are new to Serverless or GraphQL, I would recommend grabbing a cup of coffee and going through Part 1 of this series, then come back. What is AppSync? AWS AppSync is a fully managed serverless service for real-time data queries, synchronization, communications and offline programming features. This blog covers creating a GraphQL API itself, and next part of this series will focus on the AppSync Client and its features 🔈_)._ GraphQL ( stay tuned ! “ ” — by It turns out that Apollo Client 2.0 ’s modular architecture was a huge win for developers looking to customize their GraphQL client because that’s exactly how the AWS team was able to build AppSync Client ! Peggy Rayzis Note: This post by Nader Dabit is an excellent read for an AppSync primer. AppSync vs. GraphQL + Lambda If Serverless + Lambda + GraphQL works so well, then why even bother exploring other solutions? Because AppSync has a cool piece of functionality that GraphQL + Lambda doesn’t. Namely: real-time subscriptions. Both have their advantages. But which one is right for your application? when you want to have more control over what the endpoint does. For example, maybe you want to use your favorite Lambda Server to handle client requests; or perhaps you need a more closed system, and you don’t want to use AWS authentication systems. Use Lambda when you need support for real-time updates which scales to millions of people. It is much easier to do as compared to . And of course, it comes with fully AWS managed GraphQL service and enterprise-level security features. Use AppSync implementing real time updates with Lambda and IoT How can I get started with AppSync in Production? I am glad you asked! After working with AppSync, you may quickly realize that it is quite time-consuming and error-prone to wire up the entire backend components including GraphQL Schema, Resolver Mapping Templates and Data Sources (as I’ll explain further in a minute). In a production environment, you would want a piece of code or configuration to make your deployment fully automated along with being fast and scalable. For the same reason, I am happy to announce brand new which allows you to deploy AppSync Components via Serverless CLI and is now open sourced 🎉 Serverless-AppSync-Plugin My motivation behind writing this blog is to share my learnings about AppSync and provide a smooth and more flexible way to stand up a GraphQL endpoint in production within seconds. Note: Examples covered in this blog are available on GitHub . Let’s build a GraphQL Endpoint with AppSync Plugin Before jumping into this, let me explain AppSync’s building blocks: four Complete schema of the is available . It includes various types and fields to retrieve user and tweet info. GraphQL Schema mini Twitter app here Each field in the schema is resolved using request and response (written in ). These templates parse the incoming request and interpret responses from your database. GraphQL Resolvers (Mapping Templates) mapping templates Velocity Templating Language You get built-in support of DynamoDB, ElasticSearch, and Lambda. In fact, Lambda provides flexibility to add RDS, REST API, MongoDB, Druid, etc. Data Sources **Authentication and IAM Permissions**You can authenticate your API using API KEY, Cognito User Pools along with providing fine-grained access controls using IAM permissions. Anatomy of the AppSync SDK: To create the endpoint you basically have two options 1) manually wire all the components together and generate the API in AppSync UI which is or 2) write code using AWS-SDK which . time-consuming and error-prone adds more complexity to the entire process Here are the series of steps required to have an endpoint up and running: Anatomy of the AppSync SDK Serverless AppSync Plugin to the Rescue And now, look at this 😏 plugins: serverless-appsync-plugin provider:name: awsruntime: nodejs6.10 custom:appSync:name: # Your GraphQL API NameauthenticationType: mappingTemplates:- dataSource: type: # GraphQL Typefield: # Schema Fieldrequest: # Request Mapping Templateresponse: # Response Mapping Templateschema: schema.graphql # Input GraphQL SchemadataSources:- type: name: config: | | serviceRoleArn: AMAZON_COGNITO_USER_POOLS | API KEY myDynamoDB | myElasticSearch | myLambda AMAZON_DYNAMODB | AMAZON_ELASTICSEARCH | AWS_LAMBDA myDynamoDB | myElasticSearch | myLambda tableName endpoint lambdaFunctionArn IAM ROLE The Serverless AppSync Plugin allows you to configure all the as a configuration in your . You can basically deploy, update or delete AppSync components using these commands: six steps serverless.yml three serverless deploy-appsyncserverless update-appsyncserverless delete-appsync Note : All the configurations in the plugin are self-explanatory, but if you have any questions or want to contribute, please feel free to reach out to me . Finally, this is how it looks: AppSync Deployment with Serverless Plugin Mini Twitter App Architecture Now, you might be thinking “what is this fuss about mini Twitter App? How does it work? I still don’t get it!”. OK, let me explain: This app consists of a React Frontend along with an AppSync Client integration. You can further simplify the user authentication flow using and Cognito User Pool (I’ll be covering frontend architecture in detail in my blog post). AWS Amplify next For the app backend, the GraphQL API is created using the . This API connects to DynamoDB (to get user Info), ElasticSearch (to retrieve user tweets) and Lambda (to fetch any additional user info from the Twitter REST API). Serverless AppSync Plugin Note: Please follow to run the app in your local environment. these instructions Mini Twitter App Architecture Let’s look at some resolver mapping templates: getUserInfo(handle: String!) meInfo Example 1: vs. Request Mapping Template for : getUserInfo {"version" : "2017-02-28","operation" : " ","query" : {"expression": "handle = : ","expressionValues" : {":handle" : {"S" : "${ }"}}}} Query handle context.arguments.handle Request Mapping Template for : meInfo {"version" : "2017-02-28","operation" : " ","query" : {"expression": "handle = : ","expressionValues" : {":handle" : {"S" : "${ }"}}}} Query handle context.identity.username In this example, the request templates are using DynamoDB Query operation to fetch data from the Users table. In user’s handle is derived from context variable which contains his identity information (parsed through JWT token on the client side). explains more about the power of context variable and util functions in AppSync. meInfo This article Response Mapping Template for both fields: $util.toJson( ) $context.result.items[0] favourites_count Example 2: In this case, we want to fetch the value of a user’s favourite count from Twitter itself. AWS Lambda provides the flexibility to do this by querying the REST API ( ) reference .graphqlHandler = (event, context, callback) => { (event. ) { : { handle = event. . ? event. . : event. ; exports switch field case 'favourites_count' const arguments handle arguments handle handle _getFavouritesCount_(handle).then(result => { callback(**null**, result); }); **break**; } }}; (limit: Int!, nextToken: String) Example 3: tweets ElasticSearch provides an immense power of a search engine. In this case, we have indexd all the tweets in ES and the request mapping template below paginates through the user’s tweets: {"version":"2017-02-28","operation":"GET","path":"/user/twitter/_search","params":{"body":{"from": ,"size": ,"query" : {"bool" : {"must" : [{"match" :{ "handle" : }}]}}}}} $context.arguments.nextToken $context.arguments.limit $context.source.handle Response Mapping Template: {#set($hitcount = )#set($tweetList = [])#set($counter = 0)#if($hitcount > 0)#foreach($entry in )#set( $element = ${tweetList.add({"tweet" : "$entry.get('_source')['tweet']","tweet_id": "$entry.get('_id')","created_at": $entry.get('_source')['created_at']})})#set ($counter = $counter + 1)#end"items" : $util.toJson($tweetList),"nextToken" : "$counter"#end} $context.result.hits.total $context.result.hits.hits : Sample GraphQL Query { { namedescription (limit:4, nextToken:"3"){ items{tweettweet_idcreated_at}nextToken}}} query meInfo # DynamoDB favourites_count # Lambda tweets # ElasticSearch Last but not the least… The best part? All you need to get subscriptions working in the backend is to extend your GraphQL schema with 4 lines of code: type Subscription {addTweet: Tweet@aws_subscribe(mutations: [“createTweet”]} This code sets up a that listens to every new mutation, and once your client decides to subscribe to this subscription it will get real-time updates (more on this in the next post 😏) subscription createTweet AppSync Limitations **Steep learning curve**Working with AppSync requires a good amount of understanding of . For beginners, I would totally recommend . But, the good news is that AWS provides a bunch of to make our life easier. VTL this guide helpers and utilities **Missing GraphQL Info Object**AppSync doesn’t provide in the context variable for now which limits its functionality regarding integrating with other open source GraphQL frameworks like . info object Prisma **Missing support for DynamoDB Batch operations**As of now, AppSync doesn’t support all DynamoDB API’s for instance — BatchGetItem or BatchPutItem AppSync is actively adding capabilities to simplify the serverless GraphQL experience, and I’m looking forward to it. What Next? In the next part of this series, I will explain mini Twitter App’s FrontEnd components in detail including , , , with and , , etc 🔈_)._ AppSync Client AWS Amplify React Components Mutations Optimistic Response Offline Support Subscriptions Conflict Resolution ( stay tuned ! The App will look like this: Special Thanks First of all, BIG THANKS to for collaborating on this project, being an excellent mentor along with helping with code reviews and implementation. Nik Graf Thanks, , , and for your hard work on AppSync Plugin. Philipp Jon LolCoolKat AWS Mobile team ( , , , , and ) for helping out with questions and working closely to resolve issues and bugs. Richard Rohan Nader Manuel Michael Last but not the least, thanks everyone who is reading this post or encouraged me to write more. 😃 😍 Your support drives me to contribute more at Glassdoor, San Francisco attended by , , , , , Serverless and GraphQL Meetup Graphcool Serverless Danielle Nik Rohan Michael I would like to end this blog with one of my favourite quotes — “ Albert Einstein The important thing is not to stop questioning. Curiosity has its own reason for existing.” —