Front-End Web & Mobile

AWS SAM now supports GraphQL Applications with AWS AppSync

We are pleased to announce that AWS Serverless Application Model (AWS SAM) now supports building serverless GraphQL APIs with AWS AppSync.

AWS SAM provides a short-hand syntax for defining AWS serverless resources. AWS AppSync enables developers to connect their applications to data and events with secure, serverless, and performant GraphQL and Pub/Sub APIs. GraphQL APIs allow developers to reduce IO latency by reducing round trips and constraining payloads to only the data needed.

This blog post will demonstrate building a GraphQL API with the recently released AWS::Serverless::GraphQLApi resource.

New GraphQLApi Resource

With the AWS SAM GraphQLApi resource, you can declare everything needed for a GraphQL API with a single resource definition. Review the AWS::Serverless::GraphQLApi documentation for details on the resource type and its properties.

  • AWS::Serverless::GraphQLApi: The top-level resource, including properties for API keys, caching, custom domains, GraphQL schema, logging, and tracing.
  • Auth: A property defining nested authorization details, including AWS Lambda authorizer, Amazon Cognito User Pool, or OIDC provider
  • DataSource: A property defining nested datasource details like AWS Lambda or Amazon DynamoDB.
  • Function: A property to configure code, runtime, and other pipeline function properties.
  • Resolver: A property to configure code, runtime, pipeline function execution order, and other resolver properties.

SAM Application Walkthrough

This post pairs with the pre-built demonstration application to create and view social posts. Reference the git repository README for detailed instructions on how to deploy and test the application. The following diagram provides a high-level AWS architecture of the sample application.

AWS Architecture of a GraphQL application built with the AWS SAM AWS::Serverless::GraphQLApi resource
Figure 1: The example AWS AppSync application architecture

Suppose you were to define this application with AWS CloudFormation. In that case, you’d need to configure distinct CloudFormation AppSync resources for the GraphQLApi, GraphQLSchema, ApiKey, DataSource including AWS Identity and Access Management (IAM) Role and Policy, three FunctionConfiguration(s), and two pipeline Resolver(s). Instead, with the new AWS SAM transform, you can define this application with a single AWS::Serverless::GraphQLApi resource and its inline properties.

Prerequisites

It’s beneficial to have familiarity with GraphQL, JavaScript, and NoSQL . You will need the following:

  1. Access to an AWS account with permissions to create CloudFormation stacks, AWS AppSync APIs, AWS IAM roles and policies, and DynamoDB tables.
  2. Install the AWS Serverless Application Model Command Line Interface (AWS SAM CLI) with version >= 1.88.0.
  3. Install a GIT client in your work environment.
  4. Install the curl client utility in your environment.
  5. Install Node.js in your environment (to run the subscription example).

Step 1: Clone the application and review the SAM template

Review the template.yml file on GitHub or clone the application by executing the following commands in your CLI terminal to get started.

git clone https://github.com/aws-samples/aws-sam-transform-aws-appsync.git
cd aws-sam-transform-aws-appsync

Read through the template, and you’ll see that only two AWS SAM resources are defined, a GraphQL API and a DynamoDB table referenced as a datasource for API pipeline functions. AWS SAM simplifies your effort as a developer by taking care of the following undifferentiated heavy lifting for you:

  1. Generating a well-scoped IAM policy and role for datasources to access DynamoDB. The createPostItem and getPostFromTable functions reference the DynamoDBPostsTable resource, but you don’t have to define custom IAM resources.
  2. The GraphQLPostsAPI property SchemaUri references a relative path to the sam_graphql_api/schema.graphql file. When you deploy this template, AWS SAM CLI packages this schema for you, uploads it to S3, and then fetches the file from S3 when you deploy your template. Revisions to the file are versioned in S3.
  3. The GraphQLPostsAPI Functions dictionary defines named functions like createPostItem with a CodeUri property that references a relative path to the sam_graphql_api/createPostItem.js function code. AWS SAM CLI takes care of packaging, versioning, and uploading function files to S3
  4. No code is defined for pipeline Resolvers mutation and query, addPost, and getPost. AWS SAM generates the pipeline resolver JS code for you, corresponding to the Runtime you define as APPSYNC_JS.
  5. This API uses a simple API Key for authorization, an easy Auth type for starting a new GraphQL API. The Auth and API Key definition only takes two lines of configuration each. AWS SAM generates these with default values so you can start testing your API immediately.

Step 2: Installing the Application

The next step is to deploy this application to your AWS account so that you can explore the resources it creates and interact with the GraphQL API. Run the following command and accept all the defaults.

sam deploy --guided

As AWS SAM deploys your application, it will first upload your GraphQL schema and functions to Amazon S3. Then it makes an updated copy of your template so that the code URIs reference the Amazon S3 location. Finally, AWS SAM executes your template to create resources in your AWS account, like the following screenshot. Take note of the region where you installed this application.

SAM CLI resource output listing after CloudFormation execution
Figure 2: Output list of AWS resources created from the AWS SAM deploy command

Step 3: Testing the Application

When your deployment completes, you’ll see two outputs printed to your console, providing both the application’s GraphQL API endpoint and API key. Save these, as you’ll need both values to test your API in the following steps.

Screenshot of CloudFormation Stack Outputs from sam deploy command
Figure 3: CloudFormation outputs APIEndpoint and ApiKeyValue for use in testing

Now you can run the following curl commands to create and retrieve a post. You’ll need to use the API Endpoint and API Key captured from SAM CLI output values. Copy and run the command below, replacing placeholder angle brackets with your output values.

curl \
--request POST \
--header 'Content-Type: application/json' \
--header 'x-api-key: <API_KEY>' \
--data '{ "query": "mutation AddPost { addPost(author: \"Anonymous\", content: \"Lorem ipsum dolor sit amet, consectetur adipiscing elit\", title: \"A simple post\") { author content id } }" }' \
<APPSYNC_API_ENDPOINT>

Capture the value of the post id field from the response output and replace the POST_ID placeholder, then issue the following command to retrieve your post details.

curl \
--request POST \
--header 'Content-Type: application/json' \
--header 'x-api-key: <API_KEY>' \
--data '{ "query": "{ getPost(id: \"<POST_ID>\") { id author title content version ups downs } }" }' \
<APPSYNC_API_ENDPOINT>

Step 4: Testing the subscription

To test a subscription on your API, you can update the src/exports.js file with your API endpoint, API key, and the region where you installed your template.

const awsmobile = {
aws_project_region: "<REGION>", // region from `sam deploy`
aws_appsync_graphqlEndpoint: "<APPSYNC_API_ENDPOINT>",
aws_appsync_region: "<REGION>",
aws_appsync_authenticationType: "API_KEY",
aws_appsync_apiKey: "<API_KEY>",
};
export default awsmobile;

Once you’ve updated the src/exports.js file, you can run the following commands to start a web server that hosts a web page subscribed to your API

npm install
npm run build
npm run start

Once the web application runs locally, open the address http://localhost:8080/ in a browser. Next, execute some AddPost mutations against your API so that you can see them displayed on the single-page application in real-time. Again, you’ll need to replace the placeholders with your API endpoints and key before you run the commands. For this step, open a second terminal; the original terminal you opened needs to continue running the web server.

curl \
--request POST \
--header 'Content-Type: application/json' \
--header 'x-api-key: <API_KEY>' \
--data '{ "query": "mutation AddPost { addPost(author: \"AWS\", content: \"Simplifies serverless resource creation\", title: \"SAM\") { author title content id ups downs version} }" }' \
<APPSYNC_API_ENDPOINT>
curl \
--request POST \
--header 'Content-Type: application/json' \
--header 'x-api-key: <API_KEY>' \
--data '{ "query": "mutation AddPost { addPost(author: \"AWS\", content: \"Awesome managed GraphQL\", title: \"AppSync\") { author title content id ups downs version} }" }' \
<APPSYNC_API_ENDPOINT>
curl \
--request POST \
--header 'Content-Type: application/json' \
--header 'x-api-key: <API_KEY>' \
--data '{ "query": "mutation AddPost { addPost(author: \"AWS\", content: \"Speedy noSQL\", title: \"DynamoDB\") { author title content id ups downs version} }" }' \
<APPSYNC_API_ENDPOINT>

If everything worked as expected, you’ll see a page similar to the following.

Screenshot of subscriptions web applications
Figure 4: Real time subscrition result.

Step 5: Cleanup

To avoid accruing charges for the resources you created following the instructions in this blog post, use the following command to delete your application.

sam delete

Conclusion

This post reviewed the new AWS SAM features to quickly build and deploy serverless GraphQL applications with AWS AppSync. We highlighted time-saving shortcuts like generated IAM policies for datasources and file packaging to improve the developer experience for the schema file and functions.

The AWS SAM resource AWS::Serverless::GraphQLApi helps developers quickly build serverless GraphQL applications. AWS AppSync provides a managed GraphQL runtime to access data or events from one or more data sources with a single API and create engaging real-time experiences by publishing data from any event source to subscribed clients with built-in security, monitoring, caching, logging, and tracing. For more information, reference the AWS Serverless Application Model (AWS SAM) and AWS AppSync documentation.

For more learning resources, visit https://serverlessland.com/search?search=sam and https://serverlessland.com/search?search=graphql

Kevin Schwarz

Kevin Schwarz

Kevin is Sr. Solutions Architect. Kevin brings over 20 years of technical experience building business capabilities with depth in financial services, serverless, resiliency and IoT.  Outside of work, Kevin enjoys spending time with his wife and kids, running, working out, and gardening.