We use machine learning technology to do auto-translation. Click "English" on top navigation bar to check Chinese version.
Amazon Web Services SAM now supports GraphQL Applications with Amazon Web Services AppSync
We are pleased to announce that
Amazon Web Services SAM provides a short-hand syntax for defining Amazon Web Services serverless resources. Amazon Web Services 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
resource.
New GraphQLApi Resource
With the Amazon Web Services SAM GraphQLApi resource, you can declare everything needed for a GraphQL API with a single resource definition. Review the
documentation for details on the resource type and its properties.
- Amazon Web Services::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
Amazon Web Services Lambda authorizer,Amazon Cognito User Pool, or OIDC provider - DataSource : A property defining nested datasource details like Amazon Web Services 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
Figure 1: The example Amazon Web Services AppSync application architecture
Suppose you were to define this application with
resource and its inline properties.
Prerequisites
It’s beneficial to have familiarity with GraphQL, JavaScript, and NoSQL . You will need the following:
- Access to an
Amazon Web Services account with permissions to create CloudFormation stacks, Amazon Web Services AppSync APIs, Amazon Web Services IAM roles and policies, and DynamoDB tables. - Install the
Amazon Web Services Serverless Application Model Command Line Interface (Amazon Web Services SAM CLI) with version >= 1.88.0. - Install a GIT client in your work environment.
- Install the curl client utility in your environment.
- Install Node.js in your environment (to run the subscription example).
Step 1: Clone the application and review the SAM template
Review the
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 Amazon Web Services SAM resources are defined, a GraphQL API and a DynamoDB table referenced as a datasource for API pipeline functions. Amazon Web Services SAM simplifies your effort as a developer by taking care of the following undifferentiated heavy lifting for you:
- Generating a well-scoped IAM policy and role for datasources to access DynamoDB. The
createPostItem
andgetPostFromTable
functions reference theDynamoDBPostsTable
resource, but you don’t have to define custom IAM resources. - The
GraphQLPostsAPI
propertySchemaUri
references a relative path to thesam_graphql_api/schema.graphql - The
GraphQLPostsAPI
Functions dictionary defines named functions likecreatePostItem
with aCodeUri
property that references a relative path to thesam_graphql_api/createPostItem.js - No code is defined for pipeline Resolvers mutation and query,
addPost
, andgetPost
. Amazon Web Services SAM generates the pipeline resolver JS code for you, corresponding to the Runtime you define asAPPSYNC_JS
. - 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. Amazon Web Services 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 Amazon Web Services 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 Amazon Web Services 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, Amazon Web Services SAM executes your template to create resources in your Amazon Web Services account, like the following screenshot. Take note of the region where you installed this application.
Figure 2: Output list of Amazon Web Services resources created from the Amazon Web Services 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.
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
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
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
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.
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 Amazon Web Services SAM features to quickly build and deploy serverless GraphQL applications with Amazon Web Services 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 Amazon Web Services SAM resource AWS::Serverless::GraphQLApi
helps developers quickly build serverless GraphQL applications. Amazon Web Services 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
For more learning resources, visit
The mentioned AWS GenAI Services service names relating to generative AI are only available or previewed in the Global Regions. Amazon Web Services China promotes AWS GenAI Services relating to generative AI solely for China-to-global business purposes and/or advanced technology introduction.