Package software.amazon.awscdk.services.appsync
AWS AppSync Construct Library
---
AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2.
For more information on how to migrate, see the Migrating to AWS CDK v2 guide.
The @aws-cdk/aws-appsync package contains constructs for building flexible
APIs that use GraphQL.
import software.amazon.awscdk.services.appsync.*;
Example
DynamoDB
Example of a GraphQL API with AWS_IAM authorization resolving into a DynamoDb
backend data source.
GraphQL schema file schema.graphql:
type demo {
id: String!
version: String!
}
type Query {
getDemos: [ demo! ]
}
input DemoInput {
version: String!
}
type Mutation {
addDemo(input: DemoInput!): demo
}
CDK stack file app-stack.ts:
GraphqlApi api = GraphqlApi.Builder.create(this, "Api")
.name("demo")
.schema(Schema.fromAsset(join(__dirname, "schema.graphql")))
.authorizationConfig(AuthorizationConfig.builder()
.defaultAuthorization(AuthorizationMode.builder()
.authorizationType(AuthorizationType.IAM)
.build())
.build())
.xrayEnabled(true)
.build();
Table demoTable = Table.Builder.create(this, "DemoTable")
.partitionKey(Attribute.builder()
.name("id")
.type(AttributeType.STRING)
.build())
.build();
DynamoDbDataSource demoDS = api.addDynamoDbDataSource("demoDataSource", demoTable);
// Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
demoDS.createResolver(BaseResolverProps.builder()
.typeName("Query")
.fieldName("getDemos")
.requestMappingTemplate(MappingTemplate.dynamoDbScanTable())
.responseMappingTemplate(MappingTemplate.dynamoDbResultList())
.build());
// Resolver for the Mutation "addDemo" that puts the item into the DynamoDb table.
demoDS.createResolver(BaseResolverProps.builder()
.typeName("Mutation")
.fieldName("addDemo")
.requestMappingTemplate(MappingTemplate.dynamoDbPutItem(PrimaryKey.partition("id").auto(), Values.projecting("input")))
.responseMappingTemplate(MappingTemplate.dynamoDbResultItem())
.build());
Aurora Serverless
AppSync provides a data source for executing SQL commands against Amazon Aurora Serverless clusters. You can use AppSync resolvers to execute SQL statements against the Data API with GraphQL queries, mutations, and subscriptions.
// Build a data source for AppSync to access the database.
GraphqlApi api;
// Create username and password secret for DB Cluster
DatabaseSecret secret = DatabaseSecret.Builder.create(this, "AuroraSecret")
.username("clusteradmin")
.build();
// The VPC to place the cluster in
Vpc vpc = new Vpc(this, "AuroraVpc");
// Create the serverless cluster, provide all values needed to customise the database.
ServerlessCluster cluster = ServerlessCluster.Builder.create(this, "AuroraCluster")
.engine(DatabaseClusterEngine.AURORA_MYSQL)
.vpc(vpc)
.credentials(Map.of("username", "clusteradmin"))
.clusterIdentifier("db-endpoint-test")
.defaultDatabaseName("demos")
.build();
RdsDataSource rdsDS = api.addRdsDataSource("rds", cluster, secret, "demos");
// Set up a resolver for an RDS query.
rdsDS.createResolver(BaseResolverProps.builder()
.typeName("Query")
.fieldName("getDemosRds")
.requestMappingTemplate(MappingTemplate.fromString("\n {\n \"version\": \"2018-05-29\",\n \"statements\": [\n \"SELECT * FROM demos\"\n ]\n }\n "))
.responseMappingTemplate(MappingTemplate.fromString("\n $utils.toJson($utils.rds.toJsonObject($ctx.result)[0])\n "))
.build());
// Set up a resolver for an RDS mutation.
rdsDS.createResolver(BaseResolverProps.builder()
.typeName("Mutation")
.fieldName("addDemoRds")
.requestMappingTemplate(MappingTemplate.fromString("\n {\n \"version\": \"2018-05-29\",\n \"statements\": [\n \"INSERT INTO demos VALUES (:id, :version)\",\n \"SELECT * WHERE id = :id\"\n ],\n \"variableMap\": {\n \":id\": $util.toJson($util.autoId()),\n \":version\": $util.toJson($ctx.args.version)\n }\n }\n "))
.responseMappingTemplate(MappingTemplate.fromString("\n $utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])\n "))
.build());
HTTP Endpoints
GraphQL schema file schema.graphql:
type job {
id: String!
version: String!
}
input DemoInput {
version: String!
}
type Mutation {
callStepFunction(input: DemoInput!): job
}
GraphQL request mapping template request.vtl:
{
"version": "2018-05-29",
"method": "POST",
"resourcePath": "/",
"params": {
"headers": {
"content-type": "application/x-amz-json-1.0",
"x-amz-target":"AWSStepFunctions.StartExecution"
},
"body": {
"stateMachineArn": "<your step functions arn>",
"input": "{ \"id\": \"$context.arguments.id\" }"
}
}
}
GraphQL response mapping template response.vtl:
{
"id": "${context.result.id}"
}
CDK stack file app-stack.ts:
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("api")
.schema(Schema.fromAsset(join(__dirname, "schema.graphql")))
.build();
HttpDataSource httpDs = api.addHttpDataSource("ds", "https://states.amazonaws.com", HttpDataSourceOptions.builder()
.name("httpDsWithStepF")
.description("from appsync to StepFunctions Workflow")
.authorizationConfig(AwsIamConfig.builder()
.signingRegion("us-east-1")
.signingServiceName("states")
.build())
.build());
httpDs.createResolver(BaseResolverProps.builder()
.typeName("Mutation")
.fieldName("callStepFunction")
.requestMappingTemplate(MappingTemplate.fromFile("request.vtl"))
.responseMappingTemplate(MappingTemplate.fromFile("response.vtl"))
.build());
Amazon OpenSearch Service
AppSync has builtin support for Amazon OpenSearch Service (successor to Amazon Elasticsearch Service) from domains that are provisioned through your AWS account. You can use AppSync resolvers to perform GraphQL operations such as queries, mutations, and subscriptions.
import software.amazon.awscdk.services.opensearchservice.*;
GraphqlApi api;
User user = new User(this, "User");
Domain domain = Domain.Builder.create(this, "Domain")
.version(EngineVersion.OPENSEARCH_1_2)
.removalPolicy(RemovalPolicy.DESTROY)
.fineGrainedAccessControl(AdvancedSecurityOptions.builder().masterUserArn(user.getUserArn()).build())
.encryptionAtRest(EncryptionAtRestOptions.builder().enabled(true).build())
.nodeToNodeEncryption(true)
.enforceHttps(true)
.build();
OpenSearchDataSource ds = api.addOpenSearchDataSource("ds", domain);
ds.createResolver(BaseResolverProps.builder()
.typeName("Query")
.fieldName("getTests")
.requestMappingTemplate(MappingTemplate.fromString(JSON.stringify(Map.of(
"version", "2017-02-28",
"operation", "GET",
"path", "/id/post/_search",
"params", Map.of(
"headers", Map.of(),
"queryString", Map.of(),
"body", Map.of("from", 0, "size", 50))))))
.responseMappingTemplate(MappingTemplate.fromString("[\n #foreach($entry in $context.result.hits.hits)\n #if( $velocityCount > 1 ) , #end\n $utils.toJson($entry.get(\"_source\"))\n #end\n ]"))
.build());
Custom Domain Names
For many use cases you may want to associate a custom domain name with your GraphQL API. This can be done during the API creation.
import software.amazon.awscdk.services.certificatemanager.*;
import software.amazon.awscdk.services.route53.*;
// hosted zone and route53 features
String hostedZoneId;
String zoneName = "example.com";
String myDomainName = "api.example.com";
Certificate certificate = Certificate.Builder.create(this, "cert").domainName(myDomainName).build();
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("myApi")
.domainName(DomainOptions.builder()
.certificate(certificate)
.domainName(myDomainName)
.build())
.build();
// hosted zone for adding appsync domain
IHostedZone zone = HostedZone.fromHostedZoneAttributes(this, "HostedZone", HostedZoneAttributes.builder()
.hostedZoneId(hostedZoneId)
.zoneName(zoneName)
.build());
// create a cname to the appsync domain. will map to something like xxxx.cloudfront.net
// create a cname to the appsync domain. will map to something like xxxx.cloudfront.net
CnameRecord.Builder.create(this, "CnameApiRecord")
.recordName("api")
.zone(zone)
.domainName(myDomainName)
.build();
Schema
Every GraphQL Api needs a schema to define the Api. CDK offers appsync.Schema
for static convenience methods for various types of schema declaration: code-first
or schema-first.
Code-First
When declaring your GraphQL Api, CDK defaults to a code-first approach if the
schema property is not configured.
GraphqlApi api = GraphqlApi.Builder.create(this, "api").name("myApi").build();
CDK will declare a Schema class that will give your Api access functions to
define your schema code-first: addType, addToSchema, etc.
You can also declare your Schema class outside of your CDK stack, to define
your schema externally.
Schema schema = new Schema();
schema.addType(ObjectType.Builder.create("demo")
.definition(Map.of("id", GraphqlType.id()))
.build());
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("myApi")
.schema(schema)
.build();
See the code-first schema section for more details.
Schema-First
You can define your GraphQL Schema from a file on disk. For convenience, use
the appsync.Schema.fromAsset to specify the file representing your schema.
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("myApi")
.schema(Schema.fromAsset(join(__dirname, "schema.graphl")))
.build();
Imports
Any GraphQL Api that has been created outside the stack can be imported from
another stack into your CDK app. Utilizing the fromXxx function, you have
the ability to add data sources and resolvers through a IGraphqlApi interface.
GraphqlApi api;
Table table;
IGraphqlApi importedApi = GraphqlApi.fromGraphqlApiAttributes(this, "IApi", GraphqlApiAttributes.builder()
.graphqlApiId(api.getApiId())
.graphqlApiArn(api.getArn())
.build());
importedApi.addDynamoDbDataSource("TableDataSource", table);
If you don't specify graphqlArn in fromXxxAttributes, CDK will autogenerate
the expected arn for the imported api, given the apiId. For creating data
sources and resolvers, an apiId is sufficient.
Authorization
There are multiple authorization types available for GraphQL API to cater to different access use cases. They are:
- API Keys (
AuthorizationType.API_KEY) - Amazon Cognito User Pools (
AuthorizationType.USER_POOL) - OpenID Connect (
AuthorizationType.OPENID_CONNECT) - AWS Identity and Access Management (
AuthorizationType.AWS_IAM) - AWS Lambda (
AuthorizationType.AWS_LAMBDA)
These types can be used simultaneously in a single API, allowing different types of clients to access data. When you specify an authorization type, you can also specify the corresponding authorization mode to finish defining your authorization. For example, this is a GraphQL API with AWS Lambda Authorization.
import software.amazon.awscdk.services.lambda.*;
Function authFunction;
GraphqlApi.Builder.create(this, "api")
.name("api")
.schema(Schema.fromAsset(join(__dirname, "appsync.test.graphql")))
.authorizationConfig(AuthorizationConfig.builder()
.defaultAuthorization(AuthorizationMode.builder()
.authorizationType(AuthorizationType.LAMBDA)
.lambdaAuthorizerConfig(LambdaAuthorizerConfig.builder()
.handler(authFunction)
.build())
.build())
.build())
.build();
Permissions
When using AWS_IAM as the authorization type for GraphQL API, an IAM Role
with correct permissions must be used for access to API.
When configuring permissions, you can specify specific resources to only be
accessible by IAM authorization. For example, if you want to only allow mutability
for IAM authorized access you would configure the following.
In schema.graphql:
type Mutation {
updateExample(...): ...
@aws_iam
}
In IAM:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"appsync:GraphQL"
],
"Resource": [
"arn:aws:appsync:REGION:ACCOUNT_ID:apis/GRAPHQL_ID/types/Mutation/fields/updateExample"
]
}
]
}
See documentation for more details.
To make this easier, CDK provides grant API.
Use the grant function for more granular authorization.
GraphqlApi api;
Role role = Role.Builder.create(this, "Role")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
api.grant(role, IamResource.custom("types/Mutation/fields/updateExample"), "appsync:GraphQL");
IamResource
In order to use the grant functions, you need to use the class IamResource.
IamResource.custom(...arns)permits custom ARNs and requires an argument.IamResouce.ofType(type, ...fields)permits ARNs for types and their fields.IamResource.all()permits ALL resources.
Generic Permissions
Alternatively, you can use more generic grant functions to accomplish the same usage.
These include:
- grantMutation (use to grant access to Mutation fields)
- grantQuery (use to grant access to Query fields)
- grantSubscription (use to grant access to Subscription fields)
GraphqlApi api;
Role role;
// For generic types
api.grantMutation(role, "updateExample");
// For custom types and granular design
api.grant(role, IamResource.ofType("Mutation", "updateExample"), "appsync:GraphQL");
Pipeline Resolvers and AppSync Functions
AppSync Functions are local functions that perform certain operations onto a backend data source. Developers can compose operations (Functions) and execute them in sequence with Pipeline Resolvers.
GraphqlApi api;
AppsyncFunction appsyncFunction = AppsyncFunction.Builder.create(this, "function")
.name("appsync_function")
.api(api)
.dataSource(api.addNoneDataSource("none"))
.requestMappingTemplate(MappingTemplate.fromFile("request.vtl"))
.responseMappingTemplate(MappingTemplate.fromFile("response.vtl"))
.build();
AppSync Functions are used in tandem with pipeline resolvers to compose multiple operations.
GraphqlApi api;
AppsyncFunction appsyncFunction;
Resolver pipelineResolver = Resolver.Builder.create(this, "pipeline")
.api(api)
.dataSource(api.addNoneDataSource("none"))
.typeName("typeName")
.fieldName("fieldName")
.requestMappingTemplate(MappingTemplate.fromFile("beforeRequest.vtl"))
.pipelineConfig(List.of(appsyncFunction))
.responseMappingTemplate(MappingTemplate.fromFile("afterResponse.vtl"))
.build();
Learn more about Pipeline Resolvers and AppSync Functions here.
Code-First Schema
CDK offers the ability to generate your schema in a code-first approach. A code-first approach offers a developer workflow with:
- modularity: organizing schema type definitions into different files
- reusability: simplifying down boilerplate/repetitive code
- consistency: resolvers and schema definition will always be synced
The code-first approach allows for dynamic schema generation. You can generate your schema based on variables and templates to reduce code duplication.
Code-First Example
To showcase the code-first approach. Let's try to model the following schema segment.
interface Node {
id: String
}
type Query {
allFilms(after: String, first: Int, before: String, last: Int): FilmConnection
}
type FilmNode implements Node {
filmName: String
}
type FilmConnection {
edges: [FilmEdge]
films: [Film]
totalCount: Int
}
type FilmEdge {
node: Film
cursor: String
}
Above we see a schema that allows for generating paginated responses. For example,
we can query allFilms(first: 100) since FilmConnection acts as an intermediary
for holding FilmEdges we can write a resolver to return the first 100 films.
In a separate file, we can declare our object types and related functions.
We will call this file object-types.ts and we will have created it in a way that
allows us to generate other XxxConnection and XxxEdges in the future.
import software.amazon.awscdk.services.appsync.*;
Object pluralize = require("pluralize");
Map<String, GraphqlType> args = Map.of(
"after", GraphqlType.string(),
"first", GraphqlType.int(),
"before", GraphqlType.string(),
"last", GraphqlType.int());
InterfaceType Node = InterfaceType.Builder.create("Node")
.definition(Map.of("id", GraphqlType.string()))
.build();
ObjectType FilmNode = ObjectType.Builder.create("FilmNode")
.interfaceTypes(List.of(Node))
.definition(Map.of("filmName", GraphqlType.string()))
.build();
public Map<String, ObjectType> generateEdgeAndConnection(ObjectType base) {
ObjectType edge = ObjectType.Builder.create(String.format("%sEdge", base.getName()))
.definition(Map.of("node", base.attribute(), "cursor", GraphqlType.string()))
.build();
ObjectType connection = ObjectType.Builder.create(String.format("%sConnection", base.getName()))
.definition(Map.of(
"edges", edge.attribute(BaseTypeOptions.builder().isList(true).build()),
pluralize(base.getName()), base.attribute(BaseTypeOptions.builder().isList(true).build()),
"totalCount", GraphqlType.int()))
.build();
return Map.of("edge", edge, "connection", connection);
}
Finally, we will go to our cdk-stack and combine everything together
to generate our schema.
MappingTemplate dummyRequest;
MappingTemplate dummyResponse;
GraphqlApi api = GraphqlApi.Builder.create(this, "Api")
.name("demo")
.build();
InterfaceType[] objectTypes = List.of(Node, FilmNode);
Map<String, ObjectType> filmConnections = generateEdgeAndConnection(FilmNode);
api.addQuery("allFilms", ResolvableField.Builder.create()
.returnType(filmConnections.connection.attribute())
.args(args)
.dataSource(api.addNoneDataSource("none"))
.requestMappingTemplate(dummyRequest)
.responseMappingTemplate(dummyResponse)
.build());
api.addType(Node);
api.addType(FilmNode);
api.addType(filmConnections.getEdge());
api.addType(filmConnections.getConnection());
Notice how we can utilize the generateEdgeAndConnection function to generate
Object Types. In the future, if we wanted to create more Object Types, we can simply
create the base Object Type (i.e. Film) and from there we can generate its respective
Connections and Edges.
Check out a more in-depth example here.
GraphQL Types
One of the benefits of GraphQL is its strongly typed nature. We define the types within an object, query, mutation, interface, etc. as GraphQL Types.
GraphQL Types are the building blocks of types, whether they are scalar, objects, interfaces, etc. GraphQL Types can be:
- Scalar Types: Id, Int, String, AWSDate, etc.
- Object Types: types that you generate (i.e.
demofrom the example above) - Interface Types: abstract types that define the base implementation of other Intermediate Types
More concretely, GraphQL Types are simply the types appended to variables.
Referencing the object type Demo in the previous example, the GraphQL Types
is String! and is applied to both the names id and version.
Directives
Directives are attached to a field or type and affect the execution of queries,
mutations, and types. With AppSync, we use Directives to configure authorization.
CDK provides static functions to add directives to your Schema.
Directive.iam()sets a type or field's authorization to be validated throughIamDirective.apiKey()sets a type or field's authorization to be validated through aApi KeyDirective.oidc()sets a type or field's authorization to be validated throughOpenID ConnectDirective.cognito(...groups: string[])sets a type or field's authorization to be validated throughCognito User Poolsgroupsthe name of the cognito groups to give access
To learn more about authorization and directives, read these docs here.
Field and Resolvable Fields
While GraphqlType is a base implementation for GraphQL fields, we have abstractions
on top of GraphqlType that provide finer grain support.
Field
Field extends GraphqlType and will allow you to define arguments. Interface Types are not resolvable and this class will allow you to define arguments,
but not its resolvers.
For example, if we want to create the following type:
type Node {
test(argument: string): String
}
The CDK code required would be:
Field field = Field.Builder.create()
.returnType(GraphqlType.string())
.args(Map.of(
"argument", GraphqlType.string()))
.build();
InterfaceType type = InterfaceType.Builder.create("Node")
.definition(Map.of("test", field))
.build();
Resolvable Fields
ResolvableField extends Field and will allow you to define arguments and its resolvers.
Object Types can have fields that resolve and perform operations on
your backend.
You can also create resolvable fields for object types.
type Info {
node(id: String): String
}
The CDK code required would be:
GraphqlApi api;
MappingTemplate dummyRequest;
MappingTemplate dummyResponse;
ObjectType info = ObjectType.Builder.create("Info")
.definition(Map.of(
"node", ResolvableField.Builder.create()
.returnType(GraphqlType.string())
.args(Map.of(
"id", GraphqlType.string()))
.dataSource(api.addNoneDataSource("none"))
.requestMappingTemplate(dummyRequest)
.responseMappingTemplate(dummyResponse)
.build()))
.build();
To nest resolvers, we can also create top level query types that call upon other types. Building off the previous example, if we want the following graphql type definition:
type Query {
get(argument: string): Info
}
The CDK code required would be:
GraphqlApi api;
MappingTemplate dummyRequest;
MappingTemplate dummyResponse;
ObjectType query = ObjectType.Builder.create("Query")
.definition(Map.of(
"get", ResolvableField.Builder.create()
.returnType(GraphqlType.string())
.args(Map.of(
"argument", GraphqlType.string()))
.dataSource(api.addNoneDataSource("none"))
.requestMappingTemplate(dummyRequest)
.responseMappingTemplate(dummyResponse)
.build()))
.build();
Learn more about fields and resolvers here.
Intermediate Types
Intermediate Types are defined by Graphql Types and Fields. They have a set of defined fields, where each field corresponds to another type in the system. Intermediate Types will be the meat of your GraphQL Schema as they are the types defined by you.
Intermediate Types include:
Interface Types
Interface Types are abstract types that define the implementation of other intermediate types. They are useful for eliminating duplication and can be used to generate Object Types with less work.
You can create Interface Types externally.
InterfaceType node = InterfaceType.Builder.create("Node")
.definition(Map.of(
"id", GraphqlType.string(BaseTypeOptions.builder().isRequired(true).build())))
.build();
To learn more about Interface Types, read the docs here.
Object Types
Object Types are types that you declare. For example, in the code-first example
the demo variable is an Object Type. Object Types are defined by
GraphQL Types and are only usable when linked to a GraphQL Api.
You can create Object Types in two ways:
- Object Types can be created externally.
GraphqlApi api = GraphqlApi.Builder.create(this, "Api") .name("demo") .build(); ObjectType demo = ObjectType.Builder.create("Demo") .definition(Map.of( "id", GraphqlType.string(BaseTypeOptions.builder().isRequired(true).build()), "version", GraphqlType.string(BaseTypeOptions.builder().isRequired(true).build()))) .build(); api.addType(demo);This method allows for reusability and modularity, ideal for larger projects. For example, imagine moving all Object Type definition outside the stack.
object-types.ts- a file for object type definitionsimport software.amazon.awscdk.services.appsync.*; ObjectType demo = ObjectType.Builder.create("Demo") .definition(Map.of( "id", GraphqlType.string(BaseTypeOptions.builder().isRequired(true).build()), "version", GraphqlType.string(BaseTypeOptions.builder().isRequired(true).build()))) .build();cdk-stack.ts- a file containing our cdk stackGraphqlApi api; api.addType(demo);
- Object Types can be created externally from an Interface Type.
InterfaceType node = InterfaceType.Builder.create("Node") .definition(Map.of( "id", GraphqlType.string(BaseTypeOptions.builder().isRequired(true).build()))) .build(); ObjectType demo = ObjectType.Builder.create("Demo") .interfaceTypes(List.of(node)) .definition(Map.of( "version", GraphqlType.string(BaseTypeOptions.builder().isRequired(true).build()))) .build();This method allows for reusability and modularity, ideal for reducing code duplication.
To learn more about Object Types, read the docs here.
Enum Types
Enum Types are a special type of Intermediate Type. They restrict a particular set of allowed values for other Intermediate Types.
enum Episode {
NEWHOPE
EMPIRE
JEDI
}
This means that wherever we use the type Episode in our schema, we expect it to be exactly one of NEWHOPE, EMPIRE, or JEDI.
The above GraphQL Enumeration Type can be expressed in CDK as the following:
GraphqlApi api;
EnumType episode = EnumType.Builder.create("Episode")
.definition(List.of("NEWHOPE", "EMPIRE", "JEDI"))
.build();
api.addType(episode);
To learn more about Enum Types, read the docs here.
Input Types
Input Types are special types of Intermediate Types. They give users an easy way to pass complex objects for top level Mutation and Queries.
input Review {
stars: Int!
commentary: String
}
The above GraphQL Input Type can be expressed in CDK as the following:
GraphqlApi api;
InputType review = InputType.Builder.create("Review")
.definition(Map.of(
"stars", GraphqlType.int(BaseTypeOptions.builder().isRequired(true).build()),
"commentary", GraphqlType.string()))
.build();
api.addType(review);
To learn more about Input Types, read the docs here.
Union Types
Union Types are a special type of Intermediate Type. They are similar to Interface Types, but they cannot specify any common fields between types.
Note: the fields of a union type need to be Object Types. In other words, you
can't create a union type out of interfaces, other unions, or inputs.
union Search = Human | Droid | Starship
The above GraphQL Union Type encompasses the Object Types of Human, Droid and Starship. It can be expressed in CDK as the following:
GraphqlApi api;
GraphqlType string = GraphqlType.string();
ObjectType human = ObjectType.Builder.create("Human").definition(Map.of("name", string)).build();
ObjectType droid = ObjectType.Builder.create("Droid").definition(Map.of("name", string)).build();
ObjectType starship = ObjectType.Builder.create("Starship").definition(Map.of("name", string)).build();
UnionType search = UnionType.Builder.create("Search")
.definition(List.of(human, droid, starship))
.build();
api.addType(search);
To learn more about Union Types, read the docs here.
Query
Every schema requires a top level Query type. By default, the schema will look
for the Object Type named Query. The top level Query is the only exposed
type that users can access to perform GET operations on your Api.
To add fields for these queries, we can simply run the addQuery function to add
to the schema's Query type.
GraphqlApi api;
InterfaceType filmConnection;
MappingTemplate dummyRequest;
MappingTemplate dummyResponse;
GraphqlType string = GraphqlType.string();
GraphqlType int = GraphqlType.int();
api.addQuery("allFilms", ResolvableField.Builder.create()
.returnType(filmConnection.attribute())
.args(Map.of("after", string, "first", int, "before", string, "last", int))
.dataSource(api.addNoneDataSource("none"))
.requestMappingTemplate(dummyRequest)
.responseMappingTemplate(dummyResponse)
.build());
To learn more about top level operations, check out the docs here.
Mutation
Every schema can have a top level Mutation type. By default, the schema will look
for the ObjectType named Mutation. The top level Mutation Type is the only exposed
type that users can access to perform mutable operations on your Api.
To add fields for these mutations, we can simply run the addMutation function to add
to the schema's Mutation type.
GraphqlApi api;
ObjectType filmNode;
MappingTemplate dummyRequest;
MappingTemplate dummyResponse;
GraphqlType string = GraphqlType.string();
GraphqlType int = GraphqlType.int();
api.addMutation("addFilm", ResolvableField.Builder.create()
.returnType(filmNode.attribute())
.args(Map.of("name", string, "film_number", int))
.dataSource(api.addNoneDataSource("none"))
.requestMappingTemplate(dummyRequest)
.responseMappingTemplate(dummyResponse)
.build());
To learn more about top level operations, check out the docs here.
Subscription
Every schema can have a top level Subscription type. The top level Subscription Type
is the only exposed type that users can access to invoke a response to a mutation. Subscriptions
notify users when a mutation specific mutation is called. This means you can make any data source
real time by specify a GraphQL Schema directive on a mutation.
Note: The AWS AppSync client SDK automatically handles subscription connection management.
To add fields for these subscriptions, we can simply run the addSubscription function to add
to the schema's Subscription type.
GraphqlApi api;
InterfaceType film;
api.addSubscription("addedFilm", Field.Builder.create()
.returnType(film.attribute())
.args(Map.of("id", GraphqlType.id(BaseTypeOptions.builder().isRequired(true).build())))
.directives(List.of(Directive.subscribe("addFilm")))
.build());
To learn more about top level operations, check out the docs here. Deprecated: AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2. For more information on how to migrate, see https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html
-
ClassDescription(experimental) The options to add a field to an Intermediate Type.A builder for
AddFieldOptionsAn implementation forAddFieldOptions(experimental) Configuration for API Key authorization in AppSync.A builder forApiKeyConfigAn implementation forApiKeyConfig(experimental) AppSync Functions are local functions that perform certain operations onto a backend data source.(experimental) A fluent builder forAppsyncFunction.(experimental) The attributes for imported AppSync Functions.A builder forAppsyncFunctionAttributesAn implementation forAppsyncFunctionAttributes(experimental) the CDK properties for AppSync Functions.A builder forAppsyncFunctionPropsAn implementation forAppsyncFunctionProps(experimental) Utility class representing the assigment of a value to an attribute.(experimental) Specifies the attribute value assignments.(experimental) Utility class to allow assigning a value to an attribute.(experimental) Configuration of the API authorization modes.A builder forAuthorizationConfigAn implementation forAuthorizationConfig(experimental) Interface to specify default or additional authorization(s).A builder forAuthorizationModeAn implementation forAuthorizationMode(experimental) enum with all possible values for AppSync authorization type.(experimental) The authorization config in case the HTTP endpoint requires authorization.A builder forAwsIamConfigAn implementation forAwsIamConfig(experimental) Abstract AppSync datasource implementation.(experimental) properties for an AppSync datasource backed by a resource.A builder forBackedDataSourcePropsAn implementation forBackedDataSourceProps(experimental) the base properties for AppSync Functions.A builder forBaseAppsyncFunctionPropsAn implementation forBaseAppsyncFunctionProps(experimental) Abstract AppSync datasource implementation.(experimental) Base properties for an AppSync datasource.A builder forBaseDataSourcePropsAn implementation forBaseDataSourceProps(experimental) Basic properties for an AppSync resolver.A builder forBaseResolverPropsAn implementation forBaseResolverProps(experimental) Base options for GraphQL Types.A builder forBaseTypeOptionsAn implementation forBaseTypeOptions(experimental) CachingConfig for AppSync resolvers.A builder forCachingConfigAn implementation forCachingConfigA CloudFormationAWS::AppSync::ApiCache.A fluent builder forCfnApiCache.Properties for defining aCfnApiCache.A builder forCfnApiCachePropsAn implementation forCfnApiCachePropsA CloudFormationAWS::AppSync::ApiKey.A fluent builder forCfnApiKey.Properties for defining aCfnApiKey.A builder forCfnApiKeyPropsAn implementation forCfnApiKeyPropsA CloudFormationAWS::AppSync::DataSource.TheAuthorizationConfigproperty type specifies the authorization type and configuration for an AWS AppSync http data source.A builder forCfnDataSource.AuthorizationConfigPropertyAn implementation forCfnDataSource.AuthorizationConfigPropertyUse theAwsIamConfigproperty type to specifyAwsIamConfigfor a AWS AppSync authorizaton.A builder forCfnDataSource.AwsIamConfigPropertyAn implementation forCfnDataSource.AwsIamConfigPropertyA fluent builder forCfnDataSource.Describes a Delta Sync configuration.A builder forCfnDataSource.DeltaSyncConfigPropertyAn implementation forCfnDataSource.DeltaSyncConfigPropertyTheDynamoDBConfigproperty type specifies theAwsRegionandTableNamefor an Amazon DynamoDB table in your account for an AWS AppSync data source.A builder forCfnDataSource.DynamoDBConfigPropertyAn implementation forCfnDataSource.DynamoDBConfigPropertyTheElasticsearchConfigproperty type specifies theAwsRegionandEndpointsfor an Amazon OpenSearch Service domain in your account for an AWS AppSync data source.A builder forCfnDataSource.ElasticsearchConfigPropertyAn implementation forCfnDataSource.ElasticsearchConfigPropertyThe data source.A builder forCfnDataSource.EventBridgeConfigPropertyAn implementation forCfnDataSource.EventBridgeConfigPropertyUse theHttpConfigproperty type to specifyHttpConfigfor an AWS AppSync data source.A builder forCfnDataSource.HttpConfigPropertyAn implementation forCfnDataSource.HttpConfigPropertyTheLambdaConfigproperty type specifies the Lambda function ARN for an AWS AppSync data source.A builder forCfnDataSource.LambdaConfigPropertyAn implementation forCfnDataSource.LambdaConfigPropertyTheOpenSearchServiceConfigproperty type specifies theAwsRegionandEndpointsfor an Amazon OpenSearch Service domain in your account for an AWS AppSync data source.A builder forCfnDataSource.OpenSearchServiceConfigPropertyAn implementation forCfnDataSource.OpenSearchServiceConfigPropertyUse theRdsHttpEndpointConfigproperty type to specify theRdsHttpEndpointfor an AWS AppSync relational database.A builder forCfnDataSource.RdsHttpEndpointConfigPropertyAn implementation forCfnDataSource.RdsHttpEndpointConfigPropertyUse theRelationalDatabaseConfigproperty type to specifyRelationalDatabaseConfigfor an AWS AppSync data source.A builder forCfnDataSource.RelationalDatabaseConfigPropertyAn implementation forCfnDataSource.RelationalDatabaseConfigPropertyProperties for defining aCfnDataSource.A builder forCfnDataSourcePropsAn implementation forCfnDataSourcePropsA CloudFormationAWS::AppSync::DomainName.A fluent builder forCfnDomainName.A CloudFormationAWS::AppSync::DomainNameApiAssociation.A fluent builder forCfnDomainNameApiAssociation.Properties for defining aCfnDomainNameApiAssociation.A builder forCfnDomainNameApiAssociationPropsAn implementation forCfnDomainNameApiAssociationPropsProperties for defining aCfnDomainName.A builder forCfnDomainNamePropsAn implementation forCfnDomainNamePropsA CloudFormationAWS::AppSync::FunctionConfiguration.Describes a runtime used by an AWS AppSync pipeline resolver or AWS AppSync function.A builder forCfnFunctionConfiguration.AppSyncRuntimePropertyAn implementation forCfnFunctionConfiguration.AppSyncRuntimePropertyA fluent builder forCfnFunctionConfiguration.TheLambdaConflictHandlerConfigobject when configuringLAMBDAas the Conflict Handler.An implementation forCfnFunctionConfiguration.LambdaConflictHandlerConfigPropertyDescribes a Sync configuration for a resolver.A builder forCfnFunctionConfiguration.SyncConfigPropertyAn implementation forCfnFunctionConfiguration.SyncConfigPropertyProperties for defining aCfnFunctionConfiguration.A builder forCfnFunctionConfigurationPropsAn implementation forCfnFunctionConfigurationPropsA CloudFormationAWS::AppSync::GraphQLApi.Describes an additional authentication provider.A builder forCfnGraphQLApi.AdditionalAuthenticationProviderPropertyAn implementation forCfnGraphQLApi.AdditionalAuthenticationProviderPropertyA fluent builder forCfnGraphQLApi.Describes an Amazon Cognito user pool configuration.A builder forCfnGraphQLApi.CognitoUserPoolConfigPropertyAn implementation forCfnGraphQLApi.CognitoUserPoolConfigPropertyConfiguration for AWS Lambda function authorization.A builder forCfnGraphQLApi.LambdaAuthorizerConfigPropertyAn implementation forCfnGraphQLApi.LambdaAuthorizerConfigPropertyTheLogConfigproperty type specifies the logging configuration when writing GraphQL operations and tracing to Amazon CloudWatch for an AWS AppSync GraphQL API.A builder forCfnGraphQLApi.LogConfigPropertyAn implementation forCfnGraphQLApi.LogConfigPropertyTheOpenIDConnectConfigproperty type specifies the optional authorization configuration for using an OpenID Connect compliant service with your GraphQL endpoint for an AWS AppSync GraphQL API.A builder forCfnGraphQLApi.OpenIDConnectConfigPropertyAn implementation forCfnGraphQLApi.OpenIDConnectConfigPropertyTheUserPoolConfigproperty type specifies the optional authorization configuration for using Amazon Cognito user pools with your GraphQL endpoint for an AWS AppSync GraphQL API.A builder forCfnGraphQLApi.UserPoolConfigPropertyAn implementation forCfnGraphQLApi.UserPoolConfigPropertyProperties for defining aCfnGraphQLApi.A builder forCfnGraphQLApiPropsAn implementation forCfnGraphQLApiPropsA CloudFormationAWS::AppSync::GraphQLSchema.A fluent builder forCfnGraphQLSchema.Properties for defining aCfnGraphQLSchema.A builder forCfnGraphQLSchemaPropsAn implementation forCfnGraphQLSchemaPropsA CloudFormationAWS::AppSync::Resolver.Describes a runtime used by an AWS AppSync pipeline resolver or AWS AppSync function.A builder forCfnResolver.AppSyncRuntimePropertyAn implementation forCfnResolver.AppSyncRuntimePropertyA fluent builder forCfnResolver.The caching configuration for a resolver that has caching activated.A builder forCfnResolver.CachingConfigPropertyAn implementation forCfnResolver.CachingConfigPropertyTheLambdaConflictHandlerConfigwhen configuring LAMBDA as the Conflict Handler.A builder forCfnResolver.LambdaConflictHandlerConfigPropertyAn implementation forCfnResolver.LambdaConflictHandlerConfigPropertyUse thePipelineConfigproperty type to specifyPipelineConfigfor an AWS AppSync resolver.A builder forCfnResolver.PipelineConfigPropertyAn implementation forCfnResolver.PipelineConfigPropertyDescribes a Sync configuration for a resolver.A builder forCfnResolver.SyncConfigPropertyAn implementation forCfnResolver.SyncConfigPropertyProperties for defining aCfnResolver.A builder forCfnResolverPropsAn implementation forCfnResolverPropsA CloudFormationAWS::AppSync::SourceApiAssociation.A fluent builder forCfnSourceApiAssociation.Describes properties used to specify configurations related to a source API.An implementation forCfnSourceApiAssociation.SourceApiAssociationConfigPropertyProperties for defining aCfnSourceApiAssociation.A builder forCfnSourceApiAssociationPropsAn implementation forCfnSourceApiAssociationProps(experimental) Optional configuration for data sources.A builder forDataSourceOptionsAn implementation forDataSourceOptions(experimental) Directives for types.(experimental) Domain name configuration for AppSync.A builder forDomainOptionsAn implementation forDomainOptions(experimental) An AppSync datasource backed by a DynamoDB table.(experimental) A fluent builder forDynamoDbDataSource.(experimental) Properties for an AppSync DynamoDB datasource.A builder forDynamoDbDataSourcePropsAn implementation forDynamoDbDataSourcePropsDeprecated.Deprecated.Deprecated.useOpenSearchDataSourcePropswithOpenSearchDataSourceDeprecated.Deprecated.(experimental) Enum Types are abstract types that includes a set of fields that represent the strings this type can create.(experimental) A fluent builder forEnumType.(experimental) Properties for configuring an Enum Type.A builder forEnumTypeOptionsAn implementation forEnumTypeOptions(experimental) props used by implementations of BaseDataSource to provide configuration.A builder forExtendedDataSourcePropsAn implementation forExtendedDataSourceProps(experimental) Additional property for an AppSync resolver for data source reference.A builder forExtendedResolverPropsAn implementation forExtendedResolverProps(experimental) Fields build upon Graphql Types and provide typing and arguments.(experimental) A fluent builder forField.(experimental) log-level for fields in AppSync.(experimental) Properties for configuring a field.A builder forFieldOptionsAn implementation forFieldOptions(experimental) An AppSync GraphQL API.(experimental) A fluent builder forGraphqlApi.(experimental) Attributes for GraphQL imports.A builder forGraphqlApiAttributesAn implementation forGraphqlApiAttributes(experimental) Base Class for GraphQL API.(experimental) Properties for an AppSync GraphQL API.A builder forGraphqlApiPropsAn implementation forGraphqlApiProps(experimental) The GraphQL Types in AppSync's GraphQL.(experimental) Options for GraphQL Types.A builder forGraphqlTypeOptionsAn implementation forGraphqlTypeOptions(experimental) An AppSync datasource backed by a http endpoint.(experimental) A fluent builder forHttpDataSource.(experimental) Optional configuration for Http data sources.A builder forHttpDataSourceOptionsAn implementation forHttpDataSourceOptions(experimental) Properties for an AppSync http datasource.A builder forHttpDataSourcePropsAn implementation forHttpDataSourceProps(experimental) A class used to generate resource arns for AppSync.(experimental) Interface for AppSync Functions.Internal default implementation forIAppsyncFunction.A proxy class which represents a concrete javascript instance of this type.(experimental) A Graphql Field.Internal default implementation forIField.A proxy class which represents a concrete javascript instance of this type.(experimental) Interface for GraphQL.Internal default implementation forIGraphqlApi.A proxy class which represents a concrete javascript instance of this type.(experimental) Intermediate Types are types that includes a certain set of fields that define the entirety of your schema.Internal default implementation forIIntermediateType.A proxy class which represents a concrete javascript instance of this type.(experimental) Input Types are abstract types that define complex objects.(experimental) A fluent builder forInputType.(experimental) Interface Types are abstract types that includes a certain set of fields that other types must include if they implement the interface.(experimental) A fluent builder forInterfaceType.(experimental) Properties for configuring an Intermediate Type.A builder forIntermediateTypeOptionsAn implementation forIntermediateTypeOptions(experimental) Factory class for DynamoDB key conditions.(experimental) Configuration for Lambda authorization in AppSync.A builder forLambdaAuthorizerConfigAn implementation forLambdaAuthorizerConfig(experimental) An AppSync datasource backed by a Lambda function.(experimental) A fluent builder forLambdaDataSource.(experimental) Properties for an AppSync Lambda datasource.A builder forLambdaDataSourcePropsAn implementation forLambdaDataSourceProps(experimental) Logging configuration for AppSync.A builder forLogConfigAn implementation forLogConfig(experimental) MappingTemplates for AppSync resolvers.(experimental) An AppSync dummy datasource.(experimental) A fluent builder forNoneDataSource.(experimental) Properties for an AppSync dummy datasource.A builder forNoneDataSourcePropsAn implementation forNoneDataSourceProps(experimental) Object Types are types declared by you.(experimental) A fluent builder forObjectType.(experimental) Properties for configuring an Object Type.A builder forObjectTypeOptionsAn implementation forObjectTypeOptions(experimental) Configuration for OpenID Connect authorization in AppSync.A builder forOpenIdConnectConfigAn implementation forOpenIdConnectConfig(experimental) An Appsync datasource backed by OpenSearch.(experimental) A fluent builder forOpenSearchDataSource.(experimental) Properties for the OpenSearch Data Source.A builder forOpenSearchDataSourcePropsAn implementation forOpenSearchDataSourceProps(experimental) Specifies the assignment to the partition key.(experimental) Utility class to allow assigning a value or an auto-generated id to a partition key.(experimental) Specifies the assignment to the primary key.(experimental) An AppSync datasource backed by RDS.(experimental) A fluent builder forRdsDataSource.(experimental) Properties for an AppSync RDS datasource.A builder forRdsDataSourcePropsAn implementation forRdsDataSourceProps(experimental) Resolvable Fields build upon Graphql Types and provide fields that can resolve into operations on a data source.(experimental) A fluent builder forResolvableField.(experimental) Properties for configuring a resolvable field.A builder forResolvableFieldOptionsAn implementation forResolvableFieldOptions(experimental) An AppSync resolver.(experimental) A fluent builder forResolver.(experimental) Additional property for an AppSync resolver for GraphQL API reference.A builder forResolverPropsAn implementation forResolverProps(experimental) The Schema for a GraphQL Api.(experimental) A fluent builder forSchema.(experimental) The options for configuring a schema.A builder forSchemaOptionsAn implementation forSchemaOptions(experimental) Utility class to allow assigning a value or an auto-generated id to a sort key.(experimental) Enum containing the Types that can be used to define ObjectTypes.(experimental) Union Types are abstract types that are similar to Interface Types, but they cannot to specify any common fields between types.(experimental) A fluent builder forUnionType.(experimental) Properties for configuring an Union Type.A builder forUnionTypeOptionsAn implementation forUnionTypeOptions(experimental) Configuration for Cognito user-pools in AppSync.A builder forUserPoolConfigAn implementation forUserPoolConfig(experimental) enum with all possible values for Cognito user-pool default actions.(experimental) Factory class for attribute value assignments.
OpenSearchDataSource