Building GraphQL APIs with AWS AppSync
This lesson explains how AWS AppSync provides managed GraphQL APIs. With GraphQL, a client asks for exactly the data it needs, from several sources, in a single request.
Learning outcomes
After completing this lesson, you will be able to:
- Explain how a GraphQL schema, queries, mutations and subscriptions differ from REST resources.
- Describe how schemas, resolvers and data sources make up an AppSync API.
- Describe how subscriptions and AppSync Events deliver real-time updates.
- Choose between AppSync and API Gateway for a given client and data requirement.
How GraphQL works
A GraphQL API is described by a schema that defines the types of data available and the operations clients can perform. Unlike a REST API, which has one URL per resource, a GraphQL API has a single endpoint, and each request contains a query that names exactly the fields the client wants, including related data, such as an order with its items and the customer's name, in one round trip.
There are three types of operation. A query reads data. A mutation creates, updates or deletes data. A subscription keeps a connection open so that the client receives a message whenever a specified mutation occurs, which AppSync delivers over WebSockets. In AppSync, every field in the schema is connected to a resolver, which reads from or writes to a data source such as a DynamoDB table, a Lambda function, an HTTP endpoint or an Aurora database, so one query can combine data from several sources.
The following table summarises the three operation types.
| Operation | Purpose |
|---|---|
| Query | Reads data |
| Mutation | Writes data |
| Subscription | Receives real-time updates when data changes |
Because clients name the fields they want, GraphQL avoids over-fetching and the repeated round trips common with REST. This matters most for mobile clients on slow networks.
Building an AppSync API
An AppSync API is built from a schema, data sources and resolvers. The following list describes these components.
- Schema: defines the types, queries, mutations and subscriptions.
- Resolvers: written in JavaScript or VTL, they connect each field to a data source. Pipeline resolvers chain several steps.
- Data sources: DynamoDB, Lambda, Aurora, OpenSearch, HTTP endpoints and more.
Example. A schema with a query, a mutation and a subscription. Clients subscribed to onOrderUpdated are notified whenever updateOrder runs.
type Order { id: ID! status: String! total: Float }
type Query { getOrder(id: ID!): Order }
type Mutation { updateOrder(id: ID!, status: String!): Order }
type Subscription { onOrderUpdated(id: ID): Order @aws_subscribe(mutations: ["updateOrder"]) }A JavaScript resolver for getOrder with a DynamoDB data source:
import * as ddb from "@aws-appsync/utils/dynamodb";
export function request(ctx) {
return ddb.get({ key: { id: ctx.args.id } });
}
export function response(ctx) {
return ctx.result;
}Real-time updates
Subscriptions push updates to clients over WebSockets whenever a mutation runs, which suits chat, live dashboards and collaborative apps. For simple publish and subscribe channels without a GraphQL schema, AppSync Events provides serverless WebSocket APIs.
Security and performance
AWS AppSync provides features for securing APIs and improving their performance. The following list describes them.
- Authorisation: API keys, IAM, Cognito user pools, OpenID Connect and Lambda authorizers. An API can use several at once.
- Caching: server-side caching reduces calls to data sources.
- Batch resolvers: Lambda receives a list field's items in one call, avoiding the "N+1" problem of one invocation per item.
- Offline sync: Amplify client libraries let mobile apps work offline and sync later.
AppSync or API Gateway?
AppSync and API Gateway both expose back-end services to clients, but they are designed for different styles of API.
AppSync is the choice when clients need flexible queries over data that lives in several places, for example a mobile application that shows a customer's profile from DynamoDB, recent orders from Aurora and recommendations from a Lambda function on one screen. Each client requests only the fields it displays, and subscriptions push changes to connected clients without a separate WebSocket implementation. AppSync also supports caching and authorization with API keys, IAM, Cognito user pools, OpenID Connect and Lambda.
API Gateway is the choice for resource-oriented REST or HTTP APIs, and for features that AppSync does not provide, such as usage plans with API keys for per-client quotas, request validation, direct service integrations with SQS or Step Functions, and WebSocket APIs with custom routing. The following table summarises when each service is appropriate.
| Choose | When |
|---|---|
| AppSync | Clients need flexible GraphQL queries across several sources, or real-time subscriptions |
| API Gateway | You are building REST, HTTP or WebSocket APIs with usage plans, request validation or service integrations |
One screen, one request
A mobile order-tracking screen needs the order, the customer's name and the courier's live position. With a REST API it makes three calls and receives far more data than it displays. With AppSync it sends one query that names exactly the fields it needs:
query {
getOrder(id: "o-981") {
status
customer { name }
courier { latitude longitude }
}
}AppSync resolves each field from its data source (DynamoDB for the order, an HTTP service for the courier) and returns one response. A subscription on onCourierMoved pushes new positions to the screen in real time, with no polling. That combination, aggregation plus real-time updates, is when AppSync is a better fit than API Gateway.
How does an AppSync client receive live updates when data changes?
Show answer
Through a GraphQL subscription. The client subscribes over a WebSocket connection, and AppSync pushes the result of each matching mutation to it.
Exam Tips
Remember for the exam
- GraphQL or real-time subscriptions point to AppSync.
- To fetch data from several sources in one request and avoid over-fetching on mobile, use GraphQL with AppSync resolvers.
- To reduce Lambda calls for list fields, use AppSync batch resolvers.