AWS AppSync Construct Library
The aws-cdk-lib/aws-appsync package contains constructs for building flexible APIs that use GraphQL and Events.
import * as appsync from 'aws-cdk-lib/aws-appsync';
import aws_cdk.aws_appsync as appsync
import software.amazon.awscdk.services.appsync.*;
using Amazon.CDK.AWS.AppSync;
import appsync "github.com/aws/aws-cdk-go/awscdk"
GraphQL
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! ]
getDemosConsistent: [demo!]
}
input DemoInput {
version: String!
}
type Mutation {
addDemo(input: DemoInput!): demo
}
CDK stack file app-stack.ts:
const api = new appsync.GraphqlApi(this, 'Api', {
name: 'demo',
definition: appsync.Definition.fromFile(path.join(__dirname, 'schema.graphql')),
authorizationConfig: {
defaultAuthorization: {
authorizationType: appsync.AuthorizationType.IAM,
},
},
xrayEnabled: true,
});
const demoTable = new dynamodb.Table(this, 'DemoTable', {
partitionKey: {
name: 'id',
type: dynamodb.AttributeType.STRING,
},
});
const demoDS = api.addDynamoDbDataSource('demoDataSource', demoTable);
// Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
// Resolver Mapping Template Reference:
// https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html
demoDS.createResolver('QueryGetDemosResolver', {
typeName: 'Query',
fieldName: 'getDemos',
requestMappingTemplate: appsync.MappingTemplate.dynamoDbScanTable(),
responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultList(),
});
// Resolver for the Mutation "addDemo" that puts the item into the DynamoDb table.
demoDS.createResolver('MutationAddDemoResolver', {
typeName: 'Mutation',
fieldName: 'addDemo',
requestMappingTemplate: appsync.MappingTemplate.dynamoDbPutItem(
appsync.PrimaryKey.partition('id').auto(),
appsync.Values.projecting('input'),
),
responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultItem(),
});
//To enable DynamoDB read consistency with the `MappingTemplate`:
demoDS.createResolver('QueryGetDemosConsistentResolver', {
typeName: 'Query',
fieldName: 'getDemosConsistent',
requestMappingTemplate: appsync.MappingTemplate.dynamoDbScanTable(true),
responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultList(),
});
api = appsync.GraphqlApi(self, "Api",
name="demo",
definition=appsync.Definition.from_file(path.join(__dirname, "schema.graphql")),
authorization_config=appsync.AuthorizationConfig(
default_authorization=appsync.AuthorizationMode(
authorization_type=appsync.AuthorizationType.IAM
)
),
xray_enabled=True
)
demo_table = dynamodb.Table(self, "DemoTable",
partition_key=dynamodb.Attribute(
name="id",
type=dynamodb.AttributeType.STRING
)
)
demo_ds = api.add_dynamo_db_data_source("demoDataSource", demo_table)
# Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
# Resolver Mapping Template Reference:
# https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html
demo_ds.create_resolver("QueryGetDemosResolver",
type_name="Query",
field_name="getDemos",
request_mapping_template=appsync.MappingTemplate.dynamo_db_scan_table(),
response_mapping_template=appsync.MappingTemplate.dynamo_db_result_list()
)
# Resolver for the Mutation "addDemo" that puts the item into the DynamoDb table.
demo_ds.create_resolver("MutationAddDemoResolver",
type_name="Mutation",
field_name="addDemo",
request_mapping_template=appsync.MappingTemplate.dynamo_db_put_item(
appsync.PrimaryKey.partition("id").auto(),
appsync.Values.projecting("input")),
response_mapping_template=appsync.MappingTemplate.dynamo_db_result_item()
)
# To enable DynamoDB read consistency with the `MappingTemplate`:
demo_ds.create_resolver("QueryGetDemosConsistentResolver",
type_name="Query",
field_name="getDemosConsistent",
request_mapping_template=appsync.MappingTemplate.dynamo_db_scan_table(True),
response_mapping_template=appsync.MappingTemplate.dynamo_db_result_list()
)
GraphqlApi api = GraphqlApi.Builder.create(this, "Api")
.name("demo")
.definition(Definition.fromFile(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.
// Resolver Mapping Template Reference:
// https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html
demoDS.createResolver("QueryGetDemosResolver", 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("MutationAddDemoResolver", BaseResolverProps.builder()
.typeName("Mutation")
.fieldName("addDemo")
.requestMappingTemplate(MappingTemplate.dynamoDbPutItem(PrimaryKey.partition("id").auto(), Values.projecting("input")))
.responseMappingTemplate(MappingTemplate.dynamoDbResultItem())
.build());
//To enable DynamoDB read consistency with the `MappingTemplate`:
demoDS.createResolver("QueryGetDemosConsistentResolver", BaseResolverProps.builder()
.typeName("Query")
.fieldName("getDemosConsistent")
.requestMappingTemplate(MappingTemplate.dynamoDbScanTable(true))
.responseMappingTemplate(MappingTemplate.dynamoDbResultList())
.build());
var api = new GraphqlApi(this, "Api", new GraphqlApiProps {
Name = "demo",
Definition = Definition.FromFile(Join(__dirname, "schema.graphql")),
AuthorizationConfig = new AuthorizationConfig {
DefaultAuthorization = new AuthorizationMode {
AuthorizationType = AuthorizationType.IAM
}
},
XrayEnabled = true
});
var demoTable = new Table(this, "DemoTable", new TableProps {
PartitionKey = new Attribute {
Name = "id",
Type = AttributeType.STRING
}
});
var demoDS = api.AddDynamoDbDataSource("demoDataSource", demoTable);
// Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
// Resolver Mapping Template Reference:
// https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html
demoDS.CreateResolver("QueryGetDemosResolver", new BaseResolverProps {
TypeName = "Query",
FieldName = "getDemos",
RequestMappingTemplate = MappingTemplate.DynamoDbScanTable(),
ResponseMappingTemplate = MappingTemplate.DynamoDbResultList()
});
// Resolver for the Mutation "addDemo" that puts the item into the DynamoDb table.
demoDS.CreateResolver("MutationAddDemoResolver", new BaseResolverProps {
TypeName = "Mutation",
FieldName = "addDemo",
RequestMappingTemplate = MappingTemplate.DynamoDbPutItem(PrimaryKey.Partition("id").Auto(), Values.Projecting("input")),
ResponseMappingTemplate = MappingTemplate.DynamoDbResultItem()
});
//To enable DynamoDB read consistency with the `MappingTemplate`:
demoDS.CreateResolver("QueryGetDemosConsistentResolver", new BaseResolverProps {
TypeName = "Query",
FieldName = "getDemosConsistent",
RequestMappingTemplate = MappingTemplate.DynamoDbScanTable(true),
ResponseMappingTemplate = MappingTemplate.DynamoDbResultList()
});
api := appsync.NewGraphqlApi(this, jsii.String("Api"), &GraphqlApiProps{
Name: jsii.String("demo"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("schema.graphql"))),
AuthorizationConfig: &AuthorizationConfig{
DefaultAuthorization: &AuthorizationMode{
AuthorizationType: appsync.AuthorizationType_IAM,
},
},
XrayEnabled: jsii.Boolean(true),
})
demoTable := dynamodb.NewTable(this, jsii.String("DemoTable"), &TableProps{
PartitionKey: &Attribute{
Name: jsii.String("id"),
Type: dynamodb.AttributeType_STRING,
},
})
demoDS := api.AddDynamoDbDataSource(jsii.String("demoDataSource"), demoTable)
// Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
// Resolver Mapping Template Reference:
// https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html
demoDS.CreateResolver(jsii.String("QueryGetDemosResolver"), &BaseResolverProps{
TypeName: jsii.String("Query"),
FieldName: jsii.String("getDemos"),
RequestMappingTemplate: appsync.MappingTemplate_DynamoDbScanTable(),
ResponseMappingTemplate: appsync.MappingTemplate_DynamoDbResultList(),
})
// Resolver for the Mutation "addDemo" that puts the item into the DynamoDb table.
demoDS.CreateResolver(jsii.String("MutationAddDemoResolver"), &BaseResolverProps{
TypeName: jsii.String("Mutation"),
FieldName: jsii.String("addDemo"),
RequestMappingTemplate: appsync.MappingTemplate_DynamoDbPutItem(appsync.PrimaryKey_Partition(jsii.String("id")).Auto(), appsync.Values_Projecting(jsii.String("input"))),
ResponseMappingTemplate: appsync.MappingTemplate_DynamoDbResultItem(),
})
//To enable DynamoDB read consistency with the `MappingTemplate`:
demoDS.CreateResolver(jsii.String("QueryGetDemosConsistentResolver"), &BaseResolverProps{
TypeName: jsii.String("Query"),
FieldName: jsii.String("getDemosConsistent"),
RequestMappingTemplate: appsync.MappingTemplate_*DynamoDbScanTable(jsii.Boolean(true)),
ResponseMappingTemplate: appsync.MappingTemplate_*DynamoDbResultList(),
})
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.
Aurora Serverless V1 Cluster
// Create username and password secret for DB Cluster
const secret = new rds.DatabaseSecret(this, 'AuroraSecret', {
username: 'clusteradmin',
});
// The VPC to place the cluster in
const vpc = new ec2.Vpc(this, 'AuroraVpc');
// Create the serverless cluster, provide all values needed to customise the database.
const cluster = new rds.ServerlessCluster(this, 'AuroraCluster', {
engine: rds.DatabaseClusterEngine.AURORA_MYSQL,
vpc,
credentials: { username: 'clusteradmin' },
clusterIdentifier: 'db-endpoint-test',
defaultDatabaseName: 'demos',
});
// Build a data source for AppSync to access the database.
declare const api: appsync.GraphqlApi;
const rdsDS = api.addRdsDataSource('rds', cluster, secret, 'demos');
// Set up a resolver for an RDS query.
rdsDS.createResolver('QueryGetDemosRdsResolver', {
typeName: 'Query',
fieldName: 'getDemosRds',
requestMappingTemplate: appsync.MappingTemplate.fromString(`
{
"version": "2018-05-29",
"statements": [
"SELECT * FROM demos"
]
}
`),
responseMappingTemplate: appsync.MappingTemplate.fromString(`
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
`),
});
// Set up a resolver for an RDS mutation.
rdsDS.createResolver('MutationAddDemoRdsResolver', {
typeName: 'Mutation',
fieldName: 'addDemoRds',
requestMappingTemplate: appsync.MappingTemplate.fromString(`
{
"version": "2018-05-29",
"statements": [
"INSERT INTO demos VALUES (:id, :version)",
"SELECT * WHERE id = :id"
],
"variableMap": {
":id": $util.toJson($util.autoId()),
":version": $util.toJson($ctx.args.version)
}
}
`),
responseMappingTemplate: appsync.MappingTemplate.fromString(`
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
`),
});
# Build a data source for AppSync to access the database.
# api: appsync.GraphqlApi
# Create username and password secret for DB Cluster
secret = rds.DatabaseSecret(self, "AuroraSecret",
username="clusteradmin"
)
# The VPC to place the cluster in
vpc = ec2.Vpc(self, "AuroraVpc")
# Create the serverless cluster, provide all values needed to customise the database.
cluster = rds.ServerlessCluster(self, "AuroraCluster",
engine=rds.DatabaseClusterEngine.AURORA_MYSQL,
vpc=vpc,
credentials={"username": "clusteradmin"},
cluster_identifier="db-endpoint-test",
default_database_name="demos"
)
rds_ds = api.add_rds_data_source("rds", cluster, secret, "demos")
# Set up a resolver for an RDS query.
rds_ds.create_resolver("QueryGetDemosRdsResolver",
type_name="Query",
field_name="getDemosRds",
request_mapping_template=appsync.MappingTemplate.from_string("""
{
"version": "2018-05-29",
"statements": [
"SELECT * FROM demos"
]
}
"""),
response_mapping_template=appsync.MappingTemplate.from_string("""
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
""")
)
# Set up a resolver for an RDS mutation.
rds_ds.create_resolver("MutationAddDemoRdsResolver",
type_name="Mutation",
field_name="addDemoRds",
request_mapping_template=appsync.MappingTemplate.from_string("""
{
"version": "2018-05-29",
"statements": [
"INSERT INTO demos VALUES (:id, :version)",
"SELECT * WHERE id = :id"
],
"variableMap": {
":id": $util.toJson($util.autoId()),
":version": $util.toJson($ctx.args.version)
}
}
"""),
response_mapping_template=appsync.MappingTemplate.from_string("""
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
""")
)
// 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("QueryGetDemosRdsResolver", 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("MutationAddDemoRdsResolver", 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());
// Build a data source for AppSync to access the database.
GraphqlApi api;
// Create username and password secret for DB Cluster
var secret = new DatabaseSecret(this, "AuroraSecret", new DatabaseSecretProps {
Username = "clusteradmin"
});
// The VPC to place the cluster in
var vpc = new Vpc(this, "AuroraVpc");
// Create the serverless cluster, provide all values needed to customise the database.
var cluster = new ServerlessCluster(this, "AuroraCluster", new ServerlessClusterProps {
Engine = DatabaseClusterEngine.AURORA_MYSQL,
Vpc = vpc,
Credentials = new Dictionary<string, string> { { "username", "clusteradmin" } },
ClusterIdentifier = "db-endpoint-test",
DefaultDatabaseName = "demos"
});
var rdsDS = api.AddRdsDataSource("rds", cluster, secret, "demos");
// Set up a resolver for an RDS query.
rdsDS.CreateResolver("QueryGetDemosRdsResolver", new BaseResolverProps {
TypeName = "Query",
FieldName = "getDemosRds",
RequestMappingTemplate = MappingTemplate.FromString(@"
{
""version"": ""2018-05-29"",
""statements"": [
""SELECT * FROM demos""
]
}
"),
ResponseMappingTemplate = MappingTemplate.FromString(@"
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
")
});
// Set up a resolver for an RDS mutation.
rdsDS.CreateResolver("MutationAddDemoRdsResolver", new BaseResolverProps {
TypeName = "Mutation",
FieldName = "addDemoRds",
RequestMappingTemplate = MappingTemplate.FromString(@"
{
""version"": ""2018-05-29"",
""statements"": [
""INSERT INTO demos VALUES (:id, :version)"",
""SELECT * WHERE id = :id""
],
""variableMap"": {
"":id"": $util.toJson($util.autoId()),
"":version"": $util.toJson($ctx.args.version)
}
}
"),
ResponseMappingTemplate = MappingTemplate.FromString(@"
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
")
});
// Build a data source for AppSync to access the database.
var api GraphqlApi
// Create username and password secret for DB Cluster
secret := rds.NewDatabaseSecret(this, jsii.String("AuroraSecret"), &DatabaseSecretProps{
Username: jsii.String("clusteradmin"),
})
// The VPC to place the cluster in
vpc := ec2.NewVpc(this, jsii.String("AuroraVpc"))
// Create the serverless cluster, provide all values needed to customise the database.
cluster := rds.NewServerlessCluster(this, jsii.String("AuroraCluster"), &ServerlessClusterProps{
Engine: rds.DatabaseClusterEngine_AURORA_MYSQL(),
Vpc: Vpc,
Credentials: map[string]*string{
"username": jsii.String("clusteradmin"),
},
ClusterIdentifier: jsii.String("db-endpoint-test"),
DefaultDatabaseName: jsii.String("demos"),
})
rdsDS := api.AddRdsDataSource(jsii.String("rds"), cluster, secret, jsii.String("demos"))
// Set up a resolver for an RDS query.
rdsDS.CreateResolver(jsii.String("QueryGetDemosRdsResolver"), &BaseResolverProps{
TypeName: jsii.String("Query"),
FieldName: jsii.String("getDemosRds"),
RequestMappingTemplate: appsync.MappingTemplate_FromString(jsii.String(`
{
"version": "2018-05-29",
"statements": [
"SELECT * FROM demos"
]
}
`)),
ResponseMappingTemplate: appsync.MappingTemplate_*FromString(jsii.String(`
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
`)),
})
// Set up a resolver for an RDS mutation.
rdsDS.CreateResolver(jsii.String("MutationAddDemoRdsResolver"), &BaseResolverProps{
TypeName: jsii.String("Mutation"),
FieldName: jsii.String("addDemoRds"),
RequestMappingTemplate: appsync.MappingTemplate_*FromString(jsii.String(`
{
"version": "2018-05-29",
"statements": [
"INSERT INTO demos VALUES (:id, :version)",
"SELECT * WHERE id = :id"
],
"variableMap": {
":id": $util.toJson($util.autoId()),
":version": $util.toJson($ctx.args.version)
}
}
`)),
ResponseMappingTemplate: appsync.MappingTemplate_*FromString(jsii.String(`
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
`)),
})
Aurora Serverless V2 Cluster
// Create username and password secret for DB Cluster
const secret = new rds.DatabaseSecret(this, 'AuroraSecret', {
username: 'clusteradmin',
});
// The VPC to place the cluster in
const vpc = new ec2.Vpc(this, 'AuroraVpc');
// Create the serverless cluster, provide all values needed to customise the database.
const cluster = new rds.DatabaseCluster(this, 'AuroraClusterV2', {
engine: rds.DatabaseClusterEngine.auroraPostgres({ version: rds.AuroraPostgresEngineVersion.VER_15_5 }),
credentials: { username: 'clusteradmin' },
clusterIdentifier: 'db-endpoint-test',
writer: rds.ClusterInstance.serverlessV2('writer'),
serverlessV2MinCapacity: 2,
serverlessV2MaxCapacity: 10,
vpc,
defaultDatabaseName: 'demos',
enableDataApi: true, // has to be set to true to enable Data API as not enable by default
});
// Build a data source for AppSync to access the database.
declare const api: appsync.GraphqlApi;
const rdsDS = api.addRdsDataSourceV2('rds', cluster, secret, 'demos');
// Set up a resolver for an RDS query.
rdsDS.createResolver('QueryGetDemosRdsResolver', {
typeName: 'Query',
fieldName: 'getDemosRds',
requestMappingTemplate: appsync.MappingTemplate.fromString(`
{
"version": "2018-05-29",
"statements": [
"SELECT * FROM demos"
]
}
`),
responseMappingTemplate: appsync.MappingTemplate.fromString(`
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
`),
});
// Set up a resolver for an RDS mutation.
rdsDS.createResolver('MutationAddDemoRdsResolver', {
typeName: 'Mutation',
fieldName: 'addDemoRds',
requestMappingTemplate: appsync.MappingTemplate.fromString(`
{
"version": "2018-05-29",
"statements": [
"INSERT INTO demos VALUES (:id, :version)",
"SELECT * WHERE id = :id"
],
"variableMap": {
":id": $util.toJson($util.autoId()),
":version": $util.toJson($ctx.args.version)
}
}
`),
responseMappingTemplate: appsync.MappingTemplate.fromString(`
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
`),
});
# Build a data source for AppSync to access the database.
# api: appsync.GraphqlApi
# Create username and password secret for DB Cluster
secret = rds.DatabaseSecret(self, "AuroraSecret",
username="clusteradmin"
)
# The VPC to place the cluster in
vpc = ec2.Vpc(self, "AuroraVpc")
# Create the serverless cluster, provide all values needed to customise the database.
cluster = rds.DatabaseCluster(self, "AuroraClusterV2",
engine=rds.DatabaseClusterEngine.aurora_postgres(version=rds.AuroraPostgresEngineVersion.VER_15_5),
credentials={"username": "clusteradmin"},
cluster_identifier="db-endpoint-test",
writer=rds.ClusterInstance.serverless_v2("writer"),
serverless_v2_min_capacity=2,
serverless_v2_max_capacity=10,
vpc=vpc,
default_database_name="demos",
enable_data_api=True
)
rds_ds = api.add_rds_data_source_v2("rds", cluster, secret, "demos")
# Set up a resolver for an RDS query.
rds_ds.create_resolver("QueryGetDemosRdsResolver",
type_name="Query",
field_name="getDemosRds",
request_mapping_template=appsync.MappingTemplate.from_string("""
{
"version": "2018-05-29",
"statements": [
"SELECT * FROM demos"
]
}
"""),
response_mapping_template=appsync.MappingTemplate.from_string("""
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
""")
)
# Set up a resolver for an RDS mutation.
rds_ds.create_resolver("MutationAddDemoRdsResolver",
type_name="Mutation",
field_name="addDemoRds",
request_mapping_template=appsync.MappingTemplate.from_string("""
{
"version": "2018-05-29",
"statements": [
"INSERT INTO demos VALUES (:id, :version)",
"SELECT * WHERE id = :id"
],
"variableMap": {
":id": $util.toJson($util.autoId()),
":version": $util.toJson($ctx.args.version)
}
}
"""),
response_mapping_template=appsync.MappingTemplate.from_string("""
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
""")
)
// 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.
DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "AuroraClusterV2")
.engine(DatabaseClusterEngine.auroraPostgres(AuroraPostgresClusterEngineProps.builder().version(AuroraPostgresEngineVersion.VER_15_5).build()))
.credentials(Map.of("username", "clusteradmin"))
.clusterIdentifier("db-endpoint-test")
.writer(ClusterInstance.serverlessV2("writer"))
.serverlessV2MinCapacity(2)
.serverlessV2MaxCapacity(10)
.vpc(vpc)
.defaultDatabaseName("demos")
.enableDataApi(true)
.build();
RdsDataSource rdsDS = api.addRdsDataSourceV2("rds", cluster, secret, "demos");
// Set up a resolver for an RDS query.
rdsDS.createResolver("QueryGetDemosRdsResolver", 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("MutationAddDemoRdsResolver", 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());
// Build a data source for AppSync to access the database.
GraphqlApi api;
// Create username and password secret for DB Cluster
var secret = new DatabaseSecret(this, "AuroraSecret", new DatabaseSecretProps {
Username = "clusteradmin"
});
// The VPC to place the cluster in
var vpc = new Vpc(this, "AuroraVpc");
// Create the serverless cluster, provide all values needed to customise the database.
var cluster = new DatabaseCluster(this, "AuroraClusterV2", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraPostgres(new AuroraPostgresClusterEngineProps { Version = AuroraPostgresEngineVersion.VER_15_5 }),
Credentials = new Dictionary<string, string> { { "username", "clusteradmin" } },
ClusterIdentifier = "db-endpoint-test",
Writer = ClusterInstance.ServerlessV2("writer"),
ServerlessV2MinCapacity = 2,
ServerlessV2MaxCapacity = 10,
Vpc = vpc,
DefaultDatabaseName = "demos",
EnableDataApi = true
});
var rdsDS = api.AddRdsDataSourceV2("rds", cluster, secret, "demos");
// Set up a resolver for an RDS query.
rdsDS.CreateResolver("QueryGetDemosRdsResolver", new BaseResolverProps {
TypeName = "Query",
FieldName = "getDemosRds",
RequestMappingTemplate = MappingTemplate.FromString(@"
{
""version"": ""2018-05-29"",
""statements"": [
""SELECT * FROM demos""
]
}
"),
ResponseMappingTemplate = MappingTemplate.FromString(@"
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
")
});
// Set up a resolver for an RDS mutation.
rdsDS.CreateResolver("MutationAddDemoRdsResolver", new BaseResolverProps {
TypeName = "Mutation",
FieldName = "addDemoRds",
RequestMappingTemplate = MappingTemplate.FromString(@"
{
""version"": ""2018-05-29"",
""statements"": [
""INSERT INTO demos VALUES (:id, :version)"",
""SELECT * WHERE id = :id""
],
""variableMap"": {
"":id"": $util.toJson($util.autoId()),
"":version"": $util.toJson($ctx.args.version)
}
}
"),
ResponseMappingTemplate = MappingTemplate.FromString(@"
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
")
});
// Build a data source for AppSync to access the database.
var api GraphqlApi
// Create username and password secret for DB Cluster
secret := rds.NewDatabaseSecret(this, jsii.String("AuroraSecret"), &DatabaseSecretProps{
Username: jsii.String("clusteradmin"),
})
// The VPC to place the cluster in
vpc := ec2.NewVpc(this, jsii.String("AuroraVpc"))
// Create the serverless cluster, provide all values needed to customise the database.
cluster := rds.NewDatabaseCluster(this, jsii.String("AuroraClusterV2"), &DatabaseClusterProps{
Engine: rds.DatabaseClusterEngine_AuroraPostgres(&AuroraPostgresClusterEngineProps{
Version: rds.AuroraPostgresEngineVersion_VER_15_5(),
}),
Credentials: map[string]*string{
"username": jsii.String("clusteradmin"),
},
ClusterIdentifier: jsii.String("db-endpoint-test"),
Writer: rds.ClusterInstance_ServerlessV2(jsii.String("writer")),
ServerlessV2MinCapacity: jsii.Number(2),
ServerlessV2MaxCapacity: jsii.Number(10),
Vpc: Vpc,
DefaultDatabaseName: jsii.String("demos"),
EnableDataApi: jsii.Boolean(true),
})
rdsDS := api.AddRdsDataSourceV2(jsii.String("rds"), cluster, secret, jsii.String("demos"))
// Set up a resolver for an RDS query.
rdsDS.CreateResolver(jsii.String("QueryGetDemosRdsResolver"), &BaseResolverProps{
TypeName: jsii.String("Query"),
FieldName: jsii.String("getDemosRds"),
RequestMappingTemplate: appsync.MappingTemplate_FromString(jsii.String(`
{
"version": "2018-05-29",
"statements": [
"SELECT * FROM demos"
]
}
`)),
ResponseMappingTemplate: appsync.MappingTemplate_*FromString(jsii.String(`
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
`)),
})
// Set up a resolver for an RDS mutation.
rdsDS.CreateResolver(jsii.String("MutationAddDemoRdsResolver"), &BaseResolverProps{
TypeName: jsii.String("Mutation"),
FieldName: jsii.String("addDemoRds"),
RequestMappingTemplate: appsync.MappingTemplate_*FromString(jsii.String(`
{
"version": "2018-05-29",
"statements": [
"INSERT INTO demos VALUES (:id, :version)",
"SELECT * WHERE id = :id"
],
"variableMap": {
":id": $util.toJson($util.autoId()),
":version": $util.toJson($ctx.args.version)
}
}
`)),
ResponseMappingTemplate: appsync.MappingTemplate_*FromString(jsii.String(`
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
`)),
})
HTTP Endpoints
GraphQL schema file schema.graphql:
type job {
id: String!
version: String!
}
input DemoInput {
version: String!
}
type Mutation {
callStepFunction(input: DemoInput!): job
}
type Query {
_placeholder: String
}
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:
const api = new appsync.GraphqlApi(this, 'api', {
name: 'api',
definition: appsync.Definition.fromFile(path.join(__dirname, 'schema.graphql')),
});
const httpDs = api.addHttpDataSource(
'ds',
'https://states.amazonaws.com',
{
name: 'httpDsWithStepF',
description: 'from appsync to StepFunctions Workflow',
authorizationConfig: {
signingRegion: 'us-east-1',
signingServiceName: 'states',
},
},
);
httpDs.createResolver('MutationCallStepFunctionResolver', {
typeName: 'Mutation',
fieldName: 'callStepFunction',
requestMappingTemplate: appsync.MappingTemplate.fromFile('request.vtl'),
responseMappingTemplate: appsync.MappingTemplate.fromFile('response.vtl'),
});
api = appsync.GraphqlApi(self, "api",
name="api",
definition=appsync.Definition.from_file(path.join(__dirname, "schema.graphql"))
)
http_ds = api.add_http_data_source("ds", "https://states.amazonaws.com",
name="httpDsWithStepF",
description="from appsync to StepFunctions Workflow",
authorization_config=appsync.AwsIamConfig(
signing_region="us-east-1",
signing_service_name="states"
)
)
http_ds.create_resolver("MutationCallStepFunctionResolver",
type_name="Mutation",
field_name="callStepFunction",
request_mapping_template=appsync.MappingTemplate.from_file("request.vtl"),
response_mapping_template=appsync.MappingTemplate.from_file("response.vtl")
)
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("api")
.definition(Definition.fromFile(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("MutationCallStepFunctionResolver", BaseResolverProps.builder()
.typeName("Mutation")
.fieldName("callStepFunction")
.requestMappingTemplate(MappingTemplate.fromFile("request.vtl"))
.responseMappingTemplate(MappingTemplate.fromFile("response.vtl"))
.build());
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
Name = "api",
Definition = Definition.FromFile(Join(__dirname, "schema.graphql"))
});
var httpDs = api.AddHttpDataSource("ds", "https://states.amazonaws.com", new HttpDataSourceOptions {
Name = "httpDsWithStepF",
Description = "from appsync to StepFunctions Workflow",
AuthorizationConfig = new AwsIamConfig {
SigningRegion = "us-east-1",
SigningServiceName = "states"
}
});
httpDs.CreateResolver("MutationCallStepFunctionResolver", new BaseResolverProps {
TypeName = "Mutation",
FieldName = "callStepFunction",
RequestMappingTemplate = MappingTemplate.FromFile("request.vtl"),
ResponseMappingTemplate = MappingTemplate.FromFile("response.vtl")
});
api := appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
Name: jsii.String("api"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("schema.graphql"))),
})
httpDs := api.AddHttpDataSource(jsii.String("ds"), jsii.String("https://states.amazonaws.com"), &HttpDataSourceOptions{
Name: jsii.String("httpDsWithStepF"),
Description: jsii.String("from appsync to StepFunctions Workflow"),
AuthorizationConfig: &AwsIamConfig{
SigningRegion: jsii.String("us-east-1"),
SigningServiceName: jsii.String("states"),
},
})
httpDs.CreateResolver(jsii.String("MutationCallStepFunctionResolver"), &BaseResolverProps{
TypeName: jsii.String("Mutation"),
FieldName: jsii.String("callStepFunction"),
RequestMappingTemplate: appsync.MappingTemplate_FromFile(jsii.String("request.vtl")),
ResponseMappingTemplate: appsync.MappingTemplate_*FromFile(jsii.String("response.vtl")),
})
EventBridge
Integrating AppSync with EventBridge enables developers to use EventBridge rules to route commands for GraphQL mutations that need to perform any one of a variety of asynchronous tasks. More broadly, it enables teams to expose an event bus as a part of a GraphQL schema.
GraphQL schema file schema.graphql:
schema {
query: Query
mutation: Mutation
}
type Query {
event(id:ID!): Event
}
type Mutation {
emitEvent(id: ID!, name: String): PutEventsResult!
}
type Event {
id: ID!
name: String!
}
type Entry {
ErrorCode: String
ErrorMessage: String
EventId: String
}
type PutEventsResult {
Entries: [Entry!]
FailedEntry: Int
}
GraphQL request mapping template request.vtl:
{
"version" : "2018-05-29",
"operation": "PutEvents",
"events" : [
{
"source": "integ.appsync.eventbridge",
"detailType": "Mutation.emitEvent",
"detail": $util.toJson($context.arguments)
}
]
}
GraphQL response mapping template response.vtl:
$util.toJson($ctx.result)'
This response mapping template simply converts the EventBridge PutEvents result to JSON. For details about the response see the documentation. Additional logic can be added to the response template to map the response type, or to error in the event of failed events. More information can be found here.
CDK stack file app-stack.ts:
import * as events from 'aws-cdk-lib/aws-events';
const api = new appsync.GraphqlApi(this, 'EventBridgeApi', {
name: 'EventBridgeApi',
definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.eventbridge.graphql')),
});
const bus = new events.EventBus(this, 'DestinationEventBus', {});
const dataSource = api.addEventBridgeDataSource('NoneDS', bus);
dataSource.createResolver('EventResolver', {
typeName: 'Mutation',
fieldName: 'emitEvent',
requestMappingTemplate: appsync.MappingTemplate.fromFile('request.vtl'),
responseMappingTemplate: appsync.MappingTemplate.fromFile('response.vtl'),
});
import aws_cdk.aws_events as events
api = appsync.GraphqlApi(self, "EventBridgeApi",
name="EventBridgeApi",
definition=appsync.Definition.from_file(path.join(__dirname, "appsync.eventbridge.graphql"))
)
bus = events.EventBus(self, "DestinationEventBus")
data_source = api.add_event_bridge_data_source("NoneDS", bus)
data_source.create_resolver("EventResolver",
type_name="Mutation",
field_name="emitEvent",
request_mapping_template=appsync.MappingTemplate.from_file("request.vtl"),
response_mapping_template=appsync.MappingTemplate.from_file("response.vtl")
)
import software.amazon.awscdk.services.events.*;
GraphqlApi api = GraphqlApi.Builder.create(this, "EventBridgeApi")
.name("EventBridgeApi")
.definition(Definition.fromFile(join(__dirname, "appsync.eventbridge.graphql")))
.build();
EventBus bus = EventBus.Builder.create(this, "DestinationEventBus").build();
EventBridgeDataSource dataSource = api.addEventBridgeDataSource("NoneDS", bus);
dataSource.createResolver("EventResolver", BaseResolverProps.builder()
.typeName("Mutation")
.fieldName("emitEvent")
.requestMappingTemplate(MappingTemplate.fromFile("request.vtl"))
.responseMappingTemplate(MappingTemplate.fromFile("response.vtl"))
.build());
using Amazon.CDK.AWS.Events;
var api = new GraphqlApi(this, "EventBridgeApi", new GraphqlApiProps {
Name = "EventBridgeApi",
Definition = Definition.FromFile(Join(__dirname, "appsync.eventbridge.graphql"))
});
var bus = new EventBus(this, "DestinationEventBus", new EventBusProps { });
var dataSource = api.AddEventBridgeDataSource("NoneDS", bus);
dataSource.CreateResolver("EventResolver", new BaseResolverProps {
TypeName = "Mutation",
FieldName = "emitEvent",
RequestMappingTemplate = MappingTemplate.FromFile("request.vtl"),
ResponseMappingTemplate = MappingTemplate.FromFile("response.vtl")
});
import events "github.com/aws/aws-cdk-go/awscdk"
api := appsync.NewGraphqlApi(this, jsii.String("EventBridgeApi"), &GraphqlApiProps{
Name: jsii.String("EventBridgeApi"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("appsync.eventbridge.graphql"))),
})
bus := events.NewEventBus(this, jsii.String("DestinationEventBus"), &EventBusProps{
})
dataSource := api.AddEventBridgeDataSource(jsii.String("NoneDS"), bus)
dataSource.CreateResolver(jsii.String("EventResolver"), &BaseResolverProps{
TypeName: jsii.String("Mutation"),
FieldName: jsii.String("emitEvent"),
RequestMappingTemplate: appsync.MappingTemplate_FromFile(jsii.String("request.vtl")),
ResponseMappingTemplate: appsync.MappingTemplate_*FromFile(jsii.String("response.vtl")),
})
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 * as opensearch from 'aws-cdk-lib/aws-opensearchservice';
const user = new iam.User(this, 'User');
const domain = new opensearch.Domain(this, 'Domain', {
version: opensearch.EngineVersion.OPENSEARCH_2_3,
removalPolicy: RemovalPolicy.DESTROY,
fineGrainedAccessControl: { masterUserArn: user.userArn },
encryptionAtRest: { enabled: true },
nodeToNodeEncryption: true,
enforceHttps: true,
});
declare const api: appsync.GraphqlApi;
const ds = api.addOpenSearchDataSource('ds', domain);
ds.createResolver('QueryGetTestsResolver', {
typeName: 'Query',
fieldName: 'getTests',
requestMappingTemplate: appsync.MappingTemplate.fromString(JSON.stringify({
version: '2017-02-28',
operation: 'GET',
path: '/id/post/_search',
params: {
headers: {},
queryString: {},
body: { from: 0, size: 50 },
},
})),
responseMappingTemplate: appsync.MappingTemplate.fromString(`[
#foreach($entry in $context.result.hits.hits)
#if( $velocityCount > 1 ) , #end
$utils.toJson($entry.get("_source"))
#end
]`),
});
import aws_cdk.aws_opensearchservice as opensearch
# api: appsync.GraphqlApi
user = iam.User(self, "User")
domain = opensearch.Domain(self, "Domain",
version=opensearch.EngineVersion.OPENSEARCH_2_3,
removal_policy=RemovalPolicy.DESTROY,
fine_grained_access_control=opensearch.AdvancedSecurityOptions(master_user_arn=user.user_arn),
encryption_at_rest=opensearch.EncryptionAtRestOptions(enabled=True),
node_to_node_encryption=True,
enforce_https=True
)
ds = api.add_open_search_data_source("ds", domain)
ds.create_resolver("QueryGetTestsResolver",
type_name="Query",
field_name="getTests",
request_mapping_template=appsync.MappingTemplate.from_string(JSON.stringify({
"version": "2017-02-28",
"operation": "GET",
"path": "/id/post/_search",
"params": {
"headers": {},
"query_string": {},
"body": {"from": 0, "size": 50}
}
})),
response_mapping_template=appsync.MappingTemplate.from_string("""[
#foreach($entry in $context.result.hits.hits)
#if( $velocityCount > 1 ) , #end
$utils.toJson($entry.get("_source"))
#end
]""")
)
import software.amazon.awscdk.services.opensearchservice.*;
GraphqlApi api;
User user = new User(this, "User");
Domain domain = Domain.Builder.create(this, "Domain")
.version(EngineVersion.OPENSEARCH_2_3)
.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("QueryGetTestsResolver", 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());
using Amazon.CDK.AWS.OpenSearchService;
GraphqlApi api;
var user = new User(this, "User");
var domain = new Domain(this, "Domain", new DomainProps {
Version = EngineVersion.OPENSEARCH_2_3,
RemovalPolicy = RemovalPolicy.DESTROY,
FineGrainedAccessControl = new AdvancedSecurityOptions { MasterUserArn = user.UserArn },
EncryptionAtRest = new EncryptionAtRestOptions { Enabled = true },
NodeToNodeEncryption = true,
EnforceHttps = true
});
var ds = api.AddOpenSearchDataSource("ds", domain);
ds.CreateResolver("QueryGetTestsResolver", new BaseResolverProps {
TypeName = "Query",
FieldName = "getTests",
RequestMappingTemplate = MappingTemplate.FromString(JSON.Stringify(new Dictionary<string, object> {
{ "version", "2017-02-28" },
{ "operation", "GET" },
{ "path", "/id/post/_search" },
{ "params", new Struct {
Headers = new Struct { },
QueryString = new Struct { },
Body = new Struct { From = 0, Size = 50 }
} }
})),
ResponseMappingTemplate = MappingTemplate.FromString(@"[
#foreach($entry in $context.result.hits.hits)
#if( $velocityCount > 1 ) , #end
$utils.toJson($entry.get(""_source""))
#end
]")
});
import "github.com/aws/aws-cdk-go/awscdk"
var api GraphqlApi
user := iam.NewUser(this, jsii.String("User"))
domain := opensearch.NewDomain(this, jsii.String("Domain"), &DomainProps{
Version: opensearch.EngineVersion_OPENSEARCH_2_3(),
RemovalPolicy: awscdk.RemovalPolicy_DESTROY,
FineGrainedAccessControl: &AdvancedSecurityOptions{
MasterUserArn: user.userArn,
},
EncryptionAtRest: &EncryptionAtRestOptions{
Enabled: jsii.Boolean(true),
},
NodeToNodeEncryption: jsii.Boolean(true),
EnforceHttps: jsii.Boolean(true),
})
ds := api.AddOpenSearchDataSource(jsii.String("ds"), domain)
ds.CreateResolver(jsii.String("QueryGetTestsResolver"), &BaseResolverProps{
TypeName: jsii.String("Query"),
FieldName: jsii.String("getTests"),
RequestMappingTemplate: appsync.MappingTemplate_FromString(jSON.stringify(map[string]interface{}{
"version": jsii.String("2017-02-28"),
"operation": jsii.String("GET"),
"path": jsii.String("/id/post/_search"),
"params": map[string]map[string]interface{}{
"headers": map[string]interface{}{
},
"queryString": map[string]interface{}{
},
"body": map[string]*f64{
"from": jsii.Number(0),
"size": jsii.Number(50),
},
},
})),
ResponseMappingTemplate: appsync.MappingTemplate_*FromString(jsii.String(`[
#foreach($entry in $context.result.hits.hits)
#if( $velocityCount > 1 ) , #end
$utils.toJson($entry.get("_source"))
#end
]`)),
})
Merged APIs
AppSync supports Merged APIs which can be used to merge multiple source APIs into a single API.
import * as cdk from 'aws-cdk-lib';
// first source API
const firstApi = new appsync.GraphqlApi(this, 'FirstSourceAPI', {
name: 'FirstSourceAPI',
definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.merged-api-1.graphql')),
});
// second source API
const secondApi = new appsync.GraphqlApi(this, 'SecondSourceAPI', {
name: 'SecondSourceAPI',
definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.merged-api-2.graphql')),
});
// Merged API
const mergedApi = new appsync.GraphqlApi(this, 'MergedAPI', {
name: 'MergedAPI',
definition: appsync.Definition.fromSourceApis({
sourceApis: [
{
sourceApi: firstApi,
mergeType: appsync.MergeType.MANUAL_MERGE,
},
{
sourceApi: secondApi,
mergeType: appsync.MergeType.AUTO_MERGE,
}
],
}),
});
import aws_cdk as cdk
# first source API
first_api = appsync.GraphqlApi(self, "FirstSourceAPI",
name="FirstSourceAPI",
definition=appsync.Definition.from_file(path.join(__dirname, "appsync.merged-api-1.graphql"))
)
# second source API
second_api = appsync.GraphqlApi(self, "SecondSourceAPI",
name="SecondSourceAPI",
definition=appsync.Definition.from_file(path.join(__dirname, "appsync.merged-api-2.graphql"))
)
# Merged API
merged_api = appsync.GraphqlApi(self, "MergedAPI",
name="MergedAPI",
definition=appsync.Definition.from_source_apis(
source_apis=[appsync.SourceApi(
source_api=first_api,
merge_type=appsync.MergeType.MANUAL_MERGE
), appsync.SourceApi(
source_api=second_api,
merge_type=appsync.MergeType.AUTO_MERGE
)
]
)
)
import software.amazon.awscdk.*;
// first source API
GraphqlApi firstApi = GraphqlApi.Builder.create(this, "FirstSourceAPI")
.name("FirstSourceAPI")
.definition(Definition.fromFile(join(__dirname, "appsync.merged-api-1.graphql")))
.build();
// second source API
GraphqlApi secondApi = GraphqlApi.Builder.create(this, "SecondSourceAPI")
.name("SecondSourceAPI")
.definition(Definition.fromFile(join(__dirname, "appsync.merged-api-2.graphql")))
.build();
// Merged API
GraphqlApi mergedApi = GraphqlApi.Builder.create(this, "MergedAPI")
.name("MergedAPI")
.definition(Definition.fromSourceApis(SourceApiOptions.builder()
.sourceApis(List.of(SourceApi.builder()
.sourceApi(firstApi)
.mergeType(MergeType.MANUAL_MERGE)
.build(), SourceApi.builder()
.sourceApi(secondApi)
.mergeType(MergeType.AUTO_MERGE)
.build()))
.build()))
.build();
using Amazon.CDK;
// first source API
var firstApi = new GraphqlApi(this, "FirstSourceAPI", new GraphqlApiProps {
Name = "FirstSourceAPI",
Definition = Definition.FromFile(Join(__dirname, "appsync.merged-api-1.graphql"))
});
// second source API
var secondApi = new GraphqlApi(this, "SecondSourceAPI", new GraphqlApiProps {
Name = "SecondSourceAPI",
Definition = Definition.FromFile(Join(__dirname, "appsync.merged-api-2.graphql"))
});
// Merged API
var mergedApi = new GraphqlApi(this, "MergedAPI", new GraphqlApiProps {
Name = "MergedAPI",
Definition = Definition.FromSourceApis(new SourceApiOptions {
SourceApis = new [] { new SourceApi {
SourceApi = firstApi,
MergeType = MergeType.MANUAL_MERGE
}, new SourceApi {
SourceApi = secondApi,
MergeType = MergeType.AUTO_MERGE
} }
})
});
import cdk "github.com/aws/aws-cdk-go/awscdk"
// first source API
firstApi := appsync.NewGraphqlApi(this, jsii.String("FirstSourceAPI"), &GraphqlApiProps{
Name: jsii.String("FirstSourceAPI"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("appsync.merged-api-1.graphql"))),
})
// second source API
secondApi := appsync.NewGraphqlApi(this, jsii.String("SecondSourceAPI"), &GraphqlApiProps{
Name: jsii.String("SecondSourceAPI"),
Definition: appsync.Definition_*FromFile(path.join(__dirname, jsii.String("appsync.merged-api-2.graphql"))),
})
// Merged API
mergedApi := appsync.NewGraphqlApi(this, jsii.String("MergedAPI"), &GraphqlApiProps{
Name: jsii.String("MergedAPI"),
Definition: appsync.Definition_FromSourceApis(&SourceApiOptions{
SourceApis: []SourceApi{
&SourceApi{
SourceApi: firstApi,
MergeType: appsync.MergeType_MANUAL_MERGE,
},
&SourceApi{
SourceApi: secondApi,
MergeType: appsync.MergeType_AUTO_MERGE,
},
},
}),
})
Merged APIs Across Different Stacks
The SourceApiAssociation construct allows you to define a SourceApiAssociation to a Merged API in a different stack or account. This allows a source API owner the ability to associate it to an existing Merged API itself.
const sourceApi = new appsync.GraphqlApi(this, 'FirstSourceAPI', {
name: 'FirstSourceAPI',
definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.merged-api-1.graphql')),
});
const importedMergedApi = appsync.GraphqlApi.fromGraphqlApiAttributes(this, 'ImportedMergedApi', {
graphqlApiId: 'MyApiId',
graphqlApiArn: 'MyApiArn',
});
const importedExecutionRole = iam.Role.fromRoleArn(this, 'ExecutionRole', 'arn:aws:iam::ACCOUNT:role/MyExistingRole');
new appsync.SourceApiAssociation(this, 'SourceApiAssociation2', {
sourceApi: sourceApi,
mergedApi: importedMergedApi,
mergeType: appsync.MergeType.MANUAL_MERGE,
mergedApiExecutionRole: importedExecutionRole,
});
source_api = appsync.GraphqlApi(self, "FirstSourceAPI",
name="FirstSourceAPI",
definition=appsync.Definition.from_file(path.join(__dirname, "appsync.merged-api-1.graphql"))
)
imported_merged_api = appsync.GraphqlApi.from_graphql_api_attributes(self, "ImportedMergedApi",
graphql_api_id="MyApiId",
graphql_api_arn="MyApiArn"
)
imported_execution_role = iam.Role.from_role_arn(self, "ExecutionRole", "arn:aws:iam::ACCOUNT:role/MyExistingRole")
appsync.SourceApiAssociation(self, "SourceApiAssociation2",
source_api=source_api,
merged_api=imported_merged_api,
merge_type=appsync.MergeType.MANUAL_MERGE,
merged_api_execution_role=imported_execution_role
)
GraphqlApi sourceApi = GraphqlApi.Builder.create(this, "FirstSourceAPI")
.name("FirstSourceAPI")
.definition(Definition.fromFile(join(__dirname, "appsync.merged-api-1.graphql")))
.build();
IGraphqlApi importedMergedApi = GraphqlApi.fromGraphqlApiAttributes(this, "ImportedMergedApi", GraphqlApiAttributes.builder()
.graphqlApiId("MyApiId")
.graphqlApiArn("MyApiArn")
.build());
IRole importedExecutionRole = Role.fromRoleArn(this, "ExecutionRole", "arn:aws:iam::ACCOUNT:role/MyExistingRole");
SourceApiAssociation.Builder.create(this, "SourceApiAssociation2")
.sourceApi(sourceApi)
.mergedApi(importedMergedApi)
.mergeType(MergeType.MANUAL_MERGE)
.mergedApiExecutionRole(importedExecutionRole)
.build();
var sourceApi = new GraphqlApi(this, "FirstSourceAPI", new GraphqlApiProps {
Name = "FirstSourceAPI",
Definition = Definition.FromFile(Join(__dirname, "appsync.merged-api-1.graphql"))
});
var importedMergedApi = GraphqlApi.FromGraphqlApiAttributes(this, "ImportedMergedApi", new GraphqlApiAttributes {
GraphqlApiId = "MyApiId",
GraphqlApiArn = "MyApiArn"
});
var importedExecutionRole = Role.FromRoleArn(this, "ExecutionRole", "arn:aws:iam::ACCOUNT:role/MyExistingRole");
new SourceApiAssociation(this, "SourceApiAssociation2", new SourceApiAssociationProps {
SourceApi = sourceApi,
MergedApi = importedMergedApi,
MergeType = MergeType.MANUAL_MERGE,
MergedApiExecutionRole = importedExecutionRole
});
sourceApi := appsync.NewGraphqlApi(this, jsii.String("FirstSourceAPI"), &GraphqlApiProps{
Name: jsii.String("FirstSourceAPI"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("appsync.merged-api-1.graphql"))),
})
importedMergedApi := appsync.GraphqlApi_FromGraphqlApiAttributes(this, jsii.String("ImportedMergedApi"), &GraphqlApiAttributes{
GraphqlApiId: jsii.String("MyApiId"),
GraphqlApiArn: jsii.String("MyApiArn"),
})
importedExecutionRole := iam.Role_FromRoleArn(this, jsii.String("ExecutionRole"), jsii.String("arn:aws:iam::ACCOUNT:role/MyExistingRole"))
appsync.NewSourceApiAssociation(this, jsii.String("SourceApiAssociation2"), &SourceApiAssociationProps{
SourceApi: sourceApi,
MergedApi: importedMergedApi,
MergeType: appsync.MergeType_MANUAL_MERGE,
MergedApiExecutionRole: importedExecutionRole,
})
Merge Source API Update Within CDK Deployment
The SourceApiAssociationMergeOperation construct available in the awscdk-appsync-utils package provides the ability to merge a source API to a Merged API via a custom resource. If the merge operation fails with a conflict, the stack update will fail and rollback the changes to the source API in the stack in order to prevent merge conflicts and ensure the source API changes are always propagated to the Merged API.
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 * as acm from 'aws-cdk-lib/aws-certificatemanager';
import * as route53 from 'aws-cdk-lib/aws-route53';
const myDomainName = 'api.example.com';
const certificate = new acm.Certificate(this, 'cert', { domainName: myDomainName });
const schema = new appsync.SchemaFile({ filePath: 'mySchemaFile' })
const api = new appsync.GraphqlApi(this, 'api', {
name: 'myApi',
definition: appsync.Definition.fromSchema(schema),
domainName: {
certificate,
domainName: myDomainName,
},
});
// hosted zone and route53 features
declare const hostedZoneId: string;
declare const zoneName = 'example.com';
// hosted zone for adding appsync domain
const zone = route53.HostedZone.fromHostedZoneAttributes(this, `HostedZone`, {
hostedZoneId,
zoneName,
});
// create a cname to the appsync domain. will map to something like xxxx.cloudfront.net
new route53.CnameRecord(this, `CnameApiRecord`, {
recordName: 'api',
zone,
domainName: api.appSyncDomainName,
});
import aws_cdk.aws_certificatemanager as acm
import aws_cdk.aws_route53 as route53
# hosted zone and route53 features
# hosted_zone_id: str
zone_name = "example.com"
my_domain_name = "api.example.com"
certificate = acm.Certificate(self, "cert", domain_name=my_domain_name)
schema = appsync.SchemaFile(file_path="mySchemaFile")
api = appsync.GraphqlApi(self, "api",
name="myApi",
definition=appsync.Definition.from_schema(schema),
domain_name=appsync.DomainOptions(
certificate=certificate,
domain_name=my_domain_name
)
)
# hosted zone for adding appsync domain
zone = route53.HostedZone.from_hosted_zone_attributes(self, "HostedZone",
hosted_zone_id=hosted_zone_id,
zone_name=zone_name
)
# create a cname to the appsync domain. will map to something like xxxx.cloudfront.net
route53.CnameRecord(self, "CnameApiRecord",
record_name="api",
zone=zone,
domain_name=api.app_sync_domain_name
)
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();
SchemaFile schema = SchemaFile.Builder.create().filePath("mySchemaFile").build();
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("myApi")
.definition(Definition.fromSchema(schema))
.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(api.getAppSyncDomainName())
.build();
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.Route53;
// hosted zone and route53 features
string hostedZoneId;
var zoneName = "example.com";
var myDomainName = "api.example.com";
var certificate = new Certificate(this, "cert", new CertificateProps { DomainName = myDomainName });
var schema = new SchemaFile(new SchemaProps { FilePath = "mySchemaFile" });
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
Name = "myApi",
Definition = Definition.FromSchema(schema),
DomainName = new DomainOptions {
Certificate = certificate,
DomainName = myDomainName
}
});
// hosted zone for adding appsync domain
var zone = HostedZone.FromHostedZoneAttributes(this, "HostedZone", new HostedZoneAttributes {
HostedZoneId = hostedZoneId,
ZoneName = zoneName
});
// 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
new CnameRecord(this, "CnameApiRecord", new CnameRecordProps {
RecordName = "api",
Zone = zone,
DomainName = api.AppSyncDomainName
});
import acm "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
// hosted zone and route53 features
var hostedZoneId string
zoneName := "example.com"
myDomainName := "api.example.com"
certificate := acm.NewCertificate(this, jsii.String("cert"), &CertificateProps{
DomainName: myDomainName,
})
schema := appsync.NewSchemaFile(&SchemaProps{
FilePath: jsii.String("mySchemaFile"),
})
api := appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
Name: jsii.String("myApi"),
Definition: appsync.Definition_FromSchema(schema),
DomainName: &DomainOptions{
Certificate: *Certificate,
DomainName: myDomainName,
},
})
// hosted zone for adding appsync domain
zone := route53.HostedZone_FromHostedZoneAttributes(this, jsii.String("HostedZone"), &HostedZoneAttributes{
HostedZoneId: jsii.String(HostedZoneId),
ZoneName: jsii.String(ZoneName),
})
// 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
route53.NewCnameRecord(this, jsii.String("CnameApiRecord"), &CnameRecordProps{
RecordName: jsii.String("api"),
Zone: Zone,
DomainName: api.appSyncDomainName,
})
Log Group
AppSync automatically create a log group with the name /aws/appsync/apis/<graphql_api_id> upon deployment with log data set to never expire. If you want to set a different expiration period, use the logConfig.retention property.
Also you can choose the log level by setting the logConfig.fieldLogLevel property.
For more information, see CloudWatch logs.
To obtain the GraphQL API's log group as a logs.ILogGroup use the logGroup property of the GraphqlApi construct.
import * as logs from 'aws-cdk-lib/aws-logs';
new appsync.GraphqlApi(this, 'api', {
authorizationConfig: {},
name: 'myApi',
definition: appsync.Definition.fromFile(path.join(__dirname, 'myApi.graphql')),
logConfig: {
fieldLogLevel: appsync.FieldLogLevel.INFO,
retention: logs.RetentionDays.ONE_WEEK,
},
});
import aws_cdk.aws_logs as logs
appsync.GraphqlApi(self, "api",
authorization_config=appsync.AuthorizationConfig(),
name="myApi",
definition=appsync.Definition.from_file(path.join(__dirname, "myApi.graphql")),
log_config=appsync.LogConfig(
field_log_level=appsync.FieldLogLevel.INFO,
retention=logs.RetentionDays.ONE_WEEK
)
)
import software.amazon.awscdk.services.logs.*;
GraphqlApi.Builder.create(this, "api")
.authorizationConfig(AuthorizationConfig.builder().build())
.name("myApi")
.definition(Definition.fromFile(join(__dirname, "myApi.graphql")))
.logConfig(LogConfig.builder()
.fieldLogLevel(FieldLogLevel.INFO)
.retention(RetentionDays.ONE_WEEK)
.build())
.build();
using Amazon.CDK.AWS.Logs;
new GraphqlApi(this, "api", new GraphqlApiProps {
AuthorizationConfig = new AuthorizationConfig { },
Name = "myApi",
Definition = Definition.FromFile(Join(__dirname, "myApi.graphql")),
LogConfig = new LogConfig {
FieldLogLevel = FieldLogLevel.INFO,
Retention = RetentionDays.ONE_WEEK
}
});
import logs "github.com/aws/aws-cdk-go/awscdk"
appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
AuthorizationConfig: &AuthorizationConfig{
},
Name: jsii.String("myApi"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("myApi.graphql"))),
LogConfig: &LogConfig{
FieldLogLevel: appsync.FieldLogLevel_INFO,
Retention: logs.RetentionDays_ONE_WEEK,
},
})
Schema
You can define a schema using from a local file using Definition.fromFile
const api = new appsync.GraphqlApi(this, 'api', {
name: 'myApi',
definition: appsync.Definition.fromFile(path.join(__dirname, 'schema.graphl')),
});
api = appsync.GraphqlApi(self, "api",
name="myApi",
definition=appsync.Definition.from_file(path.join(__dirname, "schema.graphl"))
)
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("myApi")
.definition(Definition.fromFile(join(__dirname, "schema.graphl")))
.build();
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
Name = "myApi",
Definition = Definition.FromFile(Join(__dirname, "schema.graphl"))
});
api := appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
Name: jsii.String("myApi"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("schema.graphl"))),
})
ISchema
Alternative schema sources can be defined by implementing the ISchema interface. An example of this is the CodeFirstSchema class provided in awscdk-appsync-utils
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.
declare const api: appsync.GraphqlApi;
declare const table: dynamodb.Table;
const importedApi = appsync.GraphqlApi.fromGraphqlApiAttributes(this, 'IApi', {
graphqlApiId: api.apiId,
graphqlApiArn: api.arn,
});
importedApi.addDynamoDbDataSource('TableDataSource', table);
# api: appsync.GraphqlApi
# table: dynamodb.Table
imported_api = appsync.GraphqlApi.from_graphql_api_attributes(self, "IApi",
graphql_api_id=api.api_id,
graphql_api_arn=api.arn
)
imported_api.add_dynamo_db_data_source("TableDataSource", table)
GraphqlApi api;
Table table;
IGraphqlApi importedApi = GraphqlApi.fromGraphqlApiAttributes(this, "IApi", GraphqlApiAttributes.builder()
.graphqlApiId(api.getApiId())
.graphqlApiArn(api.getArn())
.build());
importedApi.addDynamoDbDataSource("TableDataSource", table);
GraphqlApi api;
Table table;
var importedApi = GraphqlApi.FromGraphqlApiAttributes(this, "IApi", new GraphqlApiAttributes {
GraphqlApiId = api.ApiId,
GraphqlApiArn = api.Arn
});
importedApi.AddDynamoDbDataSource("TableDataSource", table);
var api GraphqlApi
var table Table
importedApi := appsync.GraphqlApi_FromGraphqlApiAttributes(this, jsii.String("IApi"), &GraphqlApiAttributes{
GraphqlApiId: api.ApiId,
GraphqlApiArn: api.Arn,
})
importedApi.AddDynamoDbDataSource(jsii.String("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.
Private APIs
By default all AppSync GraphQL APIs are public and can be accessed from the internet. For customers that want to limit access to be from their VPC, the optional API visibility property can be set to Visibility.PRIVATE at creation time. To explicitly create a public API, the visibility property should be set to Visibility.GLOBAL. If visibility is not set, the service will default to GLOBAL.
CDK stack file app-stack.ts:
const api = new appsync.GraphqlApi(this, 'api', {
name: 'MyPrivateAPI',
definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.schema.graphql')),
visibility: appsync.Visibility.PRIVATE,
});
api = appsync.GraphqlApi(self, "api",
name="MyPrivateAPI",
definition=appsync.Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
visibility=appsync.Visibility.PRIVATE
)
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("MyPrivateAPI")
.definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
.visibility(Visibility.PRIVATE)
.build();
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
Name = "MyPrivateAPI",
Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
Visibility = Visibility.PRIVATE
});
api := appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
Name: jsii.String("MyPrivateAPI"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("appsync.schema.graphql"))),
Visibility: appsync.Visibility_PRIVATE,
})
See documentation for more details about Private APIs
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 * as lambda from 'aws-cdk-lib/aws-lambda';
declare const authFunction: lambda.Function;
new appsync.GraphqlApi(this, 'api', {
name: 'api',
definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.test.graphql')),
authorizationConfig: {
defaultAuthorization: {
authorizationType: appsync.AuthorizationType.LAMBDA,
lambdaAuthorizerConfig: {
handler: authFunction,
// can also specify `resultsCacheTtl` and `validationRegex`.
},
},
},
});
import aws_cdk.aws_lambda as lambda_
# auth_function: lambda.Function
appsync.GraphqlApi(self, "api",
name="api",
definition=appsync.Definition.from_file(path.join(__dirname, "appsync.test.graphql")),
authorization_config=appsync.AuthorizationConfig(
default_authorization=appsync.AuthorizationMode(
authorization_type=appsync.AuthorizationType.LAMBDA,
lambda_authorizer_config=appsync.LambdaAuthorizerConfig(
handler=auth_function
)
)
)
)
import software.amazon.awscdk.services.lambda.*;
Function authFunction;
GraphqlApi.Builder.create(this, "api")
.name("api")
.definition(Definition.fromFile(join(__dirname, "appsync.test.graphql")))
.authorizationConfig(AuthorizationConfig.builder()
.defaultAuthorization(AuthorizationMode.builder()
.authorizationType(AuthorizationType.LAMBDA)
.lambdaAuthorizerConfig(LambdaAuthorizerConfig.builder()
.handler(authFunction)
.build())
.build())
.build())
.build();
using Amazon.CDK.AWS.Lambda;
Function authFunction;
new GraphqlApi(this, "api", new GraphqlApiProps {
Name = "api",
Definition = Definition.FromFile(Join(__dirname, "appsync.test.graphql")),
AuthorizationConfig = new AuthorizationConfig {
DefaultAuthorization = new AuthorizationMode {
AuthorizationType = AuthorizationType.LAMBDA,
LambdaAuthorizerConfig = new LambdaAuthorizerConfig {
Handler = authFunction
}
}
}
});
import lambda "github.com/aws/aws-cdk-go/awscdk"
var authFunction Function
appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
Name: jsii.String("api"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("appsync.test.graphql"))),
AuthorizationConfig: &AuthorizationConfig{
DefaultAuthorization: &AuthorizationMode{
AuthorizationType: appsync.AuthorizationType_LAMBDA,
LambdaAuthorizerConfig: &LambdaAuthorizerConfig{
Handler: authFunction,
},
},
},
})
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.
const role = new iam.Role(this, 'Role', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});
declare const api: appsync.IGraphqlApi;
api.grant(role, appsync.IamResource.custom('types/Mutation/fields/updateExample'), 'appsync:GraphQL');
# api: appsync.IGraphqlApi
role = iam.Role(self, "Role",
assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
api.grant(role, appsync.IamResource.custom("types/Mutation/fields/updateExample"), "appsync:GraphQL")
IGraphqlApi 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");
IGraphqlApi api;
var role = new Role(this, "Role", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
api.Grant(role, IamResource.Custom("types/Mutation/fields/updateExample"), "appsync:GraphQL");
var api IGraphqlApi
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
api.Grant(role, appsync.IamResource_Custom(jsii.String("types/Mutation/fields/updateExample")), jsii.String("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)
declare const api: appsync.IGraphqlApi;
declare const role: iam.Role;
// For generic types
api.grantMutation(role, 'updateExample');
// For custom types and granular design
api.grant(role, appsync.IamResource.ofType('Mutation', 'updateExample'), 'appsync:GraphQL');
# api: appsync.IGraphqlApi
# role: iam.Role
# For generic types
api.grant_mutation(role, "updateExample")
# For custom types and granular design
api.grant(role, appsync.IamResource.of_type("Mutation", "updateExample"), "appsync:GraphQL")
IGraphqlApi 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");
IGraphqlApi 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");
var api IGraphqlApi
var role Role
// For generic types
api.GrantMutation(role, jsii.String("updateExample"))
// For custom types and granular design
api.Grant(role, appsync.IamResource_OfType(jsii.String("Mutation"), jsii.String("updateExample")), jsii.String("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.
declare const api: appsync.GraphqlApi;
const appsyncFunction = new appsync.AppsyncFunction(this, 'function', {
name: 'appsync_function',
api,
dataSource: api.addNoneDataSource('none'),
requestMappingTemplate: appsync.MappingTemplate.fromFile('request.vtl'),
responseMappingTemplate: appsync.MappingTemplate.fromFile('response.vtl'),
});
# api: appsync.GraphqlApi
appsync_function = appsync.AppsyncFunction(self, "function",
name="appsync_function",
api=api,
data_source=api.add_none_data_source("none"),
request_mapping_template=appsync.MappingTemplate.from_file("request.vtl"),
response_mapping_template=appsync.MappingTemplate.from_file("response.vtl")
)
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();
GraphqlApi api;
var appsyncFunction = new AppsyncFunction(this, "function", new AppsyncFunctionProps {
Name = "appsync_function",
Api = api,
DataSource = api.AddNoneDataSource("none"),
RequestMappingTemplate = MappingTemplate.FromFile("request.vtl"),
ResponseMappingTemplate = MappingTemplate.FromFile("response.vtl")
});
var api GraphqlApi
appsyncFunction := appsync.NewAppsyncFunction(this, jsii.String("function"), &AppsyncFunctionProps{
Name: jsii.String("appsync_function"),
Api: Api,
DataSource: api.AddNoneDataSource(jsii.String("none")),
RequestMappingTemplate: appsync.MappingTemplate_FromFile(jsii.String("request.vtl")),
ResponseMappingTemplate: appsync.MappingTemplate_*FromFile(jsii.String("response.vtl")),
})
When using the LambdaDataSource, you can control the maximum number of resolver request inputs that will be sent to a single AWS Lambda function in a BatchInvoke operation by setting the maxBatchSize property.
declare const api: appsync.GraphqlApi;
declare const lambdaDataSource: appsync.LambdaDataSource;
const appsyncFunction = new appsync.AppsyncFunction(this, 'function', {
name: 'appsync_function',
api,
dataSource: lambdaDataSource,
maxBatchSize: 10,
});
# api: appsync.GraphqlApi
# lambda_data_source: appsync.LambdaDataSource
appsync_function = appsync.AppsyncFunction(self, "function",
name="appsync_function",
api=api,
data_source=lambda_data_source,
max_batch_size=10
)
GraphqlApi api;
LambdaDataSource lambdaDataSource;
AppsyncFunction appsyncFunction = AppsyncFunction.Builder.create(this, "function")
.name("appsync_function")
.api(api)
.dataSource(lambdaDataSource)
.maxBatchSize(10)
.build();
GraphqlApi api;
LambdaDataSource lambdaDataSource;
var appsyncFunction = new AppsyncFunction(this, "function", new AppsyncFunctionProps {
Name = "appsync_function",
Api = api,
DataSource = lambdaDataSource,
MaxBatchSize = 10
});
var api GraphqlApi
var lambdaDataSource LambdaDataSource
appsyncFunction := appsync.NewAppsyncFunction(this, jsii.String("function"), &AppsyncFunctionProps{
Name: jsii.String("appsync_function"),
Api: Api,
DataSource: lambdaDataSource,
MaxBatchSize: jsii.Number(10),
})
AppSync Functions are used in tandem with pipeline resolvers to compose multiple operations.
declare const api: appsync.GraphqlApi;
declare const appsyncFunction: appsync.AppsyncFunction;
const pipelineResolver = new appsync.Resolver(this, 'pipeline', {
api,
dataSource: api.addNoneDataSource('none'),
typeName: 'typeName',
fieldName: 'fieldName',
requestMappingTemplate: appsync.MappingTemplate.fromFile('beforeRequest.vtl'),
pipelineConfig: [appsyncFunction],
responseMappingTemplate: appsync.MappingTemplate.fromFile('afterResponse.vtl'),
});
# api: appsync.GraphqlApi
# appsync_function: appsync.AppsyncFunction
pipeline_resolver = appsync.Resolver(self, "pipeline",
api=api,
data_source=api.add_none_data_source("none"),
type_name="typeName",
field_name="fieldName",
request_mapping_template=appsync.MappingTemplate.from_file("beforeRequest.vtl"),
pipeline_config=[appsync_function],
response_mapping_template=appsync.MappingTemplate.from_file("afterResponse.vtl")
)
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();
GraphqlApi api;
AppsyncFunction appsyncFunction;
var pipelineResolver = new Resolver(this, "pipeline", new ResolverProps {
Api = api,
DataSource = api.AddNoneDataSource("none"),
TypeName = "typeName",
FieldName = "fieldName",
RequestMappingTemplate = MappingTemplate.FromFile("beforeRequest.vtl"),
PipelineConfig = new [] { appsyncFunction },
ResponseMappingTemplate = MappingTemplate.FromFile("afterResponse.vtl")
});
var api GraphqlApi
var appsyncFunction AppsyncFunction
pipelineResolver := appsync.NewResolver(this, jsii.String("pipeline"), &ResolverProps{
Api: Api,
DataSource: api.AddNoneDataSource(jsii.String("none")),
TypeName: jsii.String("typeName"),
FieldName: jsii.String("fieldName"),
RequestMappingTemplate: appsync.MappingTemplate_FromFile(jsii.String("beforeRequest.vtl")),
PipelineConfig: []IFunctionConfigurationRef{
appsyncFunction,
},
ResponseMappingTemplate: appsync.MappingTemplate_*FromFile(jsii.String("afterResponse.vtl")),
})
JS Functions and Resolvers
JS Functions and resolvers are also supported. You can use a .js file within your CDK project, or specify your function code inline.
declare const api: appsync.GraphqlApi;
const myJsFunction = new appsync.AppsyncFunction(this, 'function', {
name: 'my_js_function',
api,
dataSource: api.addNoneDataSource('none'),
code: appsync.Code.fromAsset('directory/function_code.js'),
runtime: appsync.FunctionRuntime.JS_1_0_0,
});
new appsync.Resolver(this, 'PipelineResolver', {
api,
typeName: 'typeName',
fieldName: 'fieldName',
code: appsync.Code.fromInline(`
// The before step
export function request(...args) {
console.log(args);
return {}
}
// The after step
export function response(ctx) {
return ctx.prev.result
}
`),
runtime: appsync.FunctionRuntime.JS_1_0_0,
pipelineConfig: [myJsFunction],
});
# api: appsync.GraphqlApi
my_js_function = appsync.AppsyncFunction(self, "function",
name="my_js_function",
api=api,
data_source=api.add_none_data_source("none"),
code=appsync.Code.from_asset("directory/function_code.js"),
runtime=appsync.FunctionRuntime.JS_1_0_0
)
appsync.Resolver(self, "PipelineResolver",
api=api,
type_name="typeName",
field_name="fieldName",
code=appsync.Code.from_inline("""
// The before step
export function request(...args) {
console.log(args);
return {}
}
// The after step
export function response(ctx) {
return ctx.prev.result
}
"""),
runtime=appsync.FunctionRuntime.JS_1_0_0,
pipeline_config=[my_js_function]
)
GraphqlApi api;
AppsyncFunction myJsFunction = AppsyncFunction.Builder.create(this, "function")
.name("my_js_function")
.api(api)
.dataSource(api.addNoneDataSource("none"))
.code(Code.fromAsset("directory/function_code.js"))
.runtime(FunctionRuntime.JS_1_0_0)
.build();
Resolver.Builder.create(this, "PipelineResolver")
.api(api)
.typeName("typeName")
.fieldName("fieldName")
.code(Code.fromInline("\n // The before step\n export function request(...args) {\n console.log(args);\n return {}\n }\n\n // The after step\n export function response(ctx) {\n return ctx.prev.result\n }\n "))
.runtime(FunctionRuntime.JS_1_0_0)
.pipelineConfig(List.of(myJsFunction))
.build();
GraphqlApi api;
var myJsFunction = new AppsyncFunction(this, "function", new AppsyncFunctionProps {
Name = "my_js_function",
Api = api,
DataSource = api.AddNoneDataSource("none"),
Code = Code.FromAsset("directory/function_code.js"),
Runtime = FunctionRuntime.JS_1_0_0
});
new Resolver(this, "PipelineResolver", new ResolverProps {
Api = api,
TypeName = "typeName",
FieldName = "fieldName",
Code = Code.FromInline(@"
// The before step
export function request(...args) {
console.log(args);
return {}
}
// The after step
export function response(ctx) {
return ctx.prev.result
}
"),
Runtime = FunctionRuntime.JS_1_0_0,
PipelineConfig = new [] { myJsFunction }
});
var api GraphqlApi
myJsFunction := appsync.NewAppsyncFunction(this, jsii.String("function"), &AppsyncFunctionProps{
Name: jsii.String("my_js_function"),
Api: Api,
DataSource: api.AddNoneDataSource(jsii.String("none")),
Code: appsync.Code_FromAsset(jsii.String("directory/function_code.js")),
Runtime: appsync.FunctionRuntime_JS_1_0_0(),
})
appsync.NewResolver(this, jsii.String("PipelineResolver"), &ResolverProps{
Api: Api,
TypeName: jsii.String("typeName"),
FieldName: jsii.String("fieldName"),
Code: appsync.Code_FromInline(jsii.String(`
// The before step
export function request(...args) {
console.log(args);
return {}
}
// The after step
export function response(ctx) {
return ctx.prev.result
}
`)),
Runtime: appsync.FunctionRuntime_JS_1_0_0(),
PipelineConfig: []IFunctionConfigurationRef{
myJsFunction,
},
})
Learn more about Pipeline Resolvers and AppSync Functions here.
Introspection
By default, AppSync allows you to use introspection queries.
For customers that want to limit access to be introspection queries, the introspectionConfig property can be set to IntrospectionConfig.DISABLED at creation time. If introspectionConfig is not set, the service will default to ENABLED.
const api = new appsync.GraphqlApi(this, 'api', {
name: 'DisableIntrospectionApi',
definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.schema.graphql')),
introspectionConfig: appsync.IntrospectionConfig.DISABLED,
});
api = appsync.GraphqlApi(self, "api",
name="DisableIntrospectionApi",
definition=appsync.Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
introspection_config=appsync.IntrospectionConfig.DISABLED
)
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("DisableIntrospectionApi")
.definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
.introspectionConfig(IntrospectionConfig.DISABLED)
.build();
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
Name = "DisableIntrospectionApi",
Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
IntrospectionConfig = IntrospectionConfig.DISABLED
});
api := appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
Name: jsii.String("DisableIntrospectionApi"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("appsync.schema.graphql"))),
IntrospectionConfig: appsync.IntrospectionConfig_DISABLED,
})
Query Depth Limits
By default, queries are able to process an unlimited amount of nested levels. Limiting queries to a specified amount of nested levels has potential implications for the performance and flexibility of your project.
const api = new appsync.GraphqlApi(this, 'api', {
name: 'LimitQueryDepths',
definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.schema.graphql')),
queryDepthLimit: 2,
});
api = appsync.GraphqlApi(self, "api",
name="LimitQueryDepths",
definition=appsync.Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
query_depth_limit=2
)
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("LimitQueryDepths")
.definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
.queryDepthLimit(2)
.build();
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
Name = "LimitQueryDepths",
Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
QueryDepthLimit = 2
});
api := appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
Name: jsii.String("LimitQueryDepths"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("appsync.schema.graphql"))),
QueryDepthLimit: jsii.Number(2),
})
Resolver Count Limits
You can control how many resolvers each query can process. By default, each query can process up to 10000 resolvers. By setting a limit AppSync will not handle any resolvers past a certain number limit.
const api = new appsync.GraphqlApi(this, 'api', {
name: 'LimitResolverCount',
definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.schema.graphql')),
resolverCountLimit: 2,
});
api = appsync.GraphqlApi(self, "api",
name="LimitResolverCount",
definition=appsync.Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
resolver_count_limit=2
)
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("LimitResolverCount")
.definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
.resolverCountLimit(2)
.build();
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
Name = "LimitResolverCount",
Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
ResolverCountLimit = 2
});
api := appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
Name: jsii.String("LimitResolverCount"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("appsync.schema.graphql"))),
ResolverCountLimit: jsii.Number(2),
})
Environment Variables
To use environment variables in resolvers, you can use the environmentVariables property and the addEnvironmentVariable method.
const api = new appsync.GraphqlApi(this, 'api', {
name: 'api',
definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.schema.graphql')),
environmentVariables: {
EnvKey1: 'non-empty-1',
},
});
api.addEnvironmentVariable('EnvKey2', 'non-empty-2');
api = appsync.GraphqlApi(self, "api",
name="api",
definition=appsync.Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
environment_variables={
"EnvKey1": "non-empty-1"
}
)
api.add_environment_variable("EnvKey2", "non-empty-2")
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("api")
.definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
.environmentVariables(Map.of(
"EnvKey1", "non-empty-1"))
.build();
api.addEnvironmentVariable("EnvKey2", "non-empty-2");
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
Name = "api",
Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
EnvironmentVariables = new Dictionary<string, string> {
{ "EnvKey1", "non-empty-1" }
}
});
api.AddEnvironmentVariable("EnvKey2", "non-empty-2");
api := appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
Name: jsii.String("api"),
Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("appsync.schema.graphql"))),
EnvironmentVariables: map[string]*string{
"EnvKey1": jsii.String("non-empty-1"),
},
})
api.AddEnvironmentVariable(jsii.String("EnvKey2"), jsii.String("non-empty-2"))
Configure an EventBridge target that invokes an AppSync GraphQL API
Configuring the target relies on the graphQLEndpointArn property.
Use the AppSync event target to trigger an AppSync GraphQL API. You need to create an AppSync.GraphqlApi configured with AWS_IAM authorization mode.
The code snippet below creates a AppSync GraphQL API target that is invoked, calling the publish mutation.
import * as events from 'aws-cdk-lib/aws-events';
import * as targets from 'aws-cdk-lib/aws-events-targets';
declare const rule: events.Rule;
declare const api: appsync.GraphqlApi;
rule.addTarget(new targets.AppSync(api, {
graphQLOperation: 'mutation Publish($message: String!){ publish(message: $message) { message } }',
variables: events.RuleTargetInput.fromObject({
message: 'hello world',
}),
}));
import aws_cdk.aws_events as events
import aws_cdk.aws_events_targets as targets
# rule: events.Rule
# api: appsync.GraphqlApi
rule.add_target(targets.AppSync(api,
graph_ql_operation="mutation Publish($message: String!){ publish(message: $message) { message } }",
variables=events.RuleTargetInput.from_object({
"message": "hello world"
})
))
import software.amazon.awscdk.services.events.*;
import software.amazon.awscdk.services.events.targets.*;
Rule rule;
GraphqlApi api;
rule.addTarget(AppSync.Builder.create(api)
.graphQLOperation("mutation Publish($message: String!){ publish(message: $message) { message } }")
.variables(RuleTargetInput.fromObject(Map.of(
"message", "hello world")))
.build());
using Amazon.CDK.AWS.Events;
using Amazon.CDK.AWS.Events.Targets;
Rule rule;
GraphqlApi api;
rule.AddTarget(new AppSync(api, new AppSyncGraphQLApiProps {
GraphQLOperation = "mutation Publish($message: String!){ publish(message: $message) { message } }",
Variables = RuleTargetInput.FromObject(new Dictionary<string, string> {
{ "message", "hello world" }
})
}));
import events "github.com/aws/aws-cdk-go/awscdk"
import targets "github.com/aws/aws-cdk-go/awscdk"
var rule Rule
var api GraphqlApi
rule.AddTarget(targets.NewAppSync(api, &AppSyncGraphQLApiProps{
GraphQLOperation: jsii.String("mutation Publish($message: String!){ publish(message: $message) { message } }"),
Variables: events.RuleTargetInput_FromObject(map[string]*string{
"message": jsii.String("hello world"),
}),
}))
Owner Contact
You can set the owner contact information for an API resource. This field accepts any string input with a length of 0 - 256 characters.
const api = new appsync.GraphqlApi(this, 'OwnerContact', {
name: 'OwnerContact',
definition: appsync.Definition.fromSchema(appsync.SchemaFile.fromAsset(path.join(__dirname, 'appsync.test.graphql'))),
ownerContact: 'test-owner-contact',
});
api = appsync.GraphqlApi(self, "OwnerContact",
name="OwnerContact",
definition=appsync.Definition.from_schema(appsync.SchemaFile.from_asset(path.join(__dirname, "appsync.test.graphql"))),
owner_contact="test-owner-contact"
)
GraphqlApi api = GraphqlApi.Builder.create(this, "OwnerContact")
.name("OwnerContact")
.definition(Definition.fromSchema(SchemaFile.fromAsset(join(__dirname, "appsync.test.graphql"))))
.ownerContact("test-owner-contact")
.build();
var api = new GraphqlApi(this, "OwnerContact", new GraphqlApiProps {
Name = "OwnerContact",
Definition = Definition.FromSchema(SchemaFile.FromAsset(Join(__dirname, "appsync.test.graphql"))),
OwnerContact = "test-owner-contact"
});
api := appsync.NewGraphqlApi(this, jsii.String("OwnerContact"), &GraphqlApiProps{
Name: jsii.String("OwnerContact"),
Definition: appsync.Definition_FromSchema(appsync.SchemaFile_FromAsset(path.join(__dirname, jsii.String("appsync.test.graphql")))),
OwnerContact: jsii.String("test-owner-contact"),
})
Enhanced Metrics
Enables and controls the enhanced metrics feature. Enhanced metrics emit granular data on API usage and performance such as AppSync request and error counts, latency, and cache hits/misses. All enhanced metric data is sent to your CloudWatch account, and you can configure the types of data that will be sent.
const schema = new appsync.SchemaFile({ filePath: 'mySchemaFile' })
new appsync.GraphqlApi(this, 'api', {
name: 'myApi',
definition: appsync.Definition.fromSchema(schema),
enhancedMetricsConfig: {
dataSourceLevelMetricsBehavior: appsync.DataSourceLevelMetricsBehavior.FULL_REQUEST_DATA_SOURCE_METRICS,
operationLevelMetricsConfig: appsync.OperationLevelMetricsConfig.ENABLED,
resolverLevelMetricsBehavior: appsync.ResolverLevelMetricsBehavior.FULL_REQUEST_RESOLVER_METRICS,
},
});
schema = appsync.SchemaFile(file_path="mySchemaFile")
appsync.GraphqlApi(self, "api",
name="myApi",
definition=appsync.Definition.from_schema(schema),
enhanced_metrics_config=appsync.EnhancedMetricsConfig(
data_source_level_metrics_behavior=appsync.DataSourceLevelMetricsBehavior.FULL_REQUEST_DATA_SOURCE_METRICS,
operation_level_metrics_config=appsync.OperationLevelMetricsConfig.ENABLED,
resolver_level_metrics_behavior=appsync.ResolverLevelMetricsBehavior.FULL_REQUEST_RESOLVER_METRICS
)
)
SchemaFile schema = SchemaFile.Builder.create().filePath("mySchemaFile").build();
GraphqlApi.Builder.create(this, "api")
.name("myApi")
.definition(Definition.fromSchema(schema))
.enhancedMetricsConfig(EnhancedMetricsConfig.builder()
.dataSourceLevelMetricsBehavior(DataSourceLevelMetricsBehavior.FULL_REQUEST_DATA_SOURCE_METRICS)
.operationLevelMetricsConfig(OperationLevelMetricsConfig.ENABLED)
.resolverLevelMetricsBehavior(ResolverLevelMetricsBehavior.FULL_REQUEST_RESOLVER_METRICS)
.build())
.build();
var schema = new SchemaFile(new SchemaProps { FilePath = "mySchemaFile" });
new GraphqlApi(this, "api", new GraphqlApiProps {
Name = "myApi",
Definition = Definition.FromSchema(schema),
EnhancedMetricsConfig = new EnhancedMetricsConfig {
DataSourceLevelMetricsBehavior = DataSourceLevelMetricsBehavior.FULL_REQUEST_DATA_SOURCE_METRICS,
OperationLevelMetricsConfig = OperationLevelMetricsConfig.ENABLED,
ResolverLevelMetricsBehavior = ResolverLevelMetricsBehavior.FULL_REQUEST_RESOLVER_METRICS
}
});
schema := appsync.NewSchemaFile(&SchemaProps{
FilePath: jsii.String("mySchemaFile"),
})
appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
Name: jsii.String("myApi"),
Definition: appsync.Definition_FromSchema(schema),
EnhancedMetricsConfig: &EnhancedMetricsConfig{
DataSourceLevelMetricsBehavior: appsync.DataSourceLevelMetricsBehavior_FULL_REQUEST_DATA_SOURCE_METRICS,
OperationLevelMetricsConfig: appsync.OperationLevelMetricsConfig_ENABLED,
ResolverLevelMetricsBehavior: appsync.ResolverLevelMetricsBehavior_FULL_REQUEST_RESOLVER_METRICS,
},
})
If you wish to enable enhanced metrics only for subset of data sources or resolvers you can use the following configuration.
const schema = new appsync.SchemaFile({ filePath: 'mySchemaFile' })
const api = new appsync.GraphqlApi(this, 'api', {
name: 'myApi',
definition: appsync.Definition.fromSchema(schema),
enhancedMetricsConfig: {
dataSourceLevelMetricsBehavior: appsync.DataSourceLevelMetricsBehavior.PER_DATA_SOURCE_METRICS,
operationLevelMetricsConfig: appsync.OperationLevelMetricsConfig.ENABLED,
resolverLevelMetricsBehavior: appsync.ResolverLevelMetricsBehavior.PER_RESOLVER_METRICS,
},
});
const noneDS = api.addNoneDataSource('none', {
metricsConfig: appsync.DataSourceMetricsConfig.ENABLED,
});
noneDS.createResolver('noneResolver', {
typeName: 'Mutation',
fieldName: 'addDemoMetricsConfig',
metricsConfig: appsync.ResolverMetricsConfig.ENABLED,
});
schema = appsync.SchemaFile(file_path="mySchemaFile")
api = appsync.GraphqlApi(self, "api",
name="myApi",
definition=appsync.Definition.from_schema(schema),
enhanced_metrics_config=appsync.EnhancedMetricsConfig(
data_source_level_metrics_behavior=appsync.DataSourceLevelMetricsBehavior.PER_DATA_SOURCE_METRICS,
operation_level_metrics_config=appsync.OperationLevelMetricsConfig.ENABLED,
resolver_level_metrics_behavior=appsync.ResolverLevelMetricsBehavior.PER_RESOLVER_METRICS
)
)
none_ds = api.add_none_data_source("none",
metrics_config=appsync.DataSourceMetricsConfig.ENABLED
)
none_ds.create_resolver("noneResolver",
type_name="Mutation",
field_name="addDemoMetricsConfig",
metrics_config=appsync.ResolverMetricsConfig.ENABLED
)
SchemaFile schema = SchemaFile.Builder.create().filePath("mySchemaFile").build();
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
.name("myApi")
.definition(Definition.fromSchema(schema))
.enhancedMetricsConfig(EnhancedMetricsConfig.builder()
.dataSourceLevelMetricsBehavior(DataSourceLevelMetricsBehavior.PER_DATA_SOURCE_METRICS)
.operationLevelMetricsConfig(OperationLevelMetricsConfig.ENABLED)
.resolverLevelMetricsBehavior(ResolverLevelMetricsBehavior.PER_RESOLVER_METRICS)
.build())
.build();
NoneDataSource noneDS = api.addNoneDataSource("none", DataSourceOptions.builder()
.metricsConfig(DataSourceMetricsConfig.ENABLED)
.build());
noneDS.createResolver("noneResolver", BaseResolverProps.builder()
.typeName("Mutation")
.fieldName("addDemoMetricsConfig")
.metricsConfig(ResolverMetricsConfig.ENABLED)
.build());
var schema = new SchemaFile(new SchemaProps { FilePath = "mySchemaFile" });
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
Name = "myApi",
Definition = Definition.FromSchema(schema),
EnhancedMetricsConfig = new EnhancedMetricsConfig {
DataSourceLevelMetricsBehavior = DataSourceLevelMetricsBehavior.PER_DATA_SOURCE_METRICS,
OperationLevelMetricsConfig = OperationLevelMetricsConfig.ENABLED,
ResolverLevelMetricsBehavior = ResolverLevelMetricsBehavior.PER_RESOLVER_METRICS
}
});
var noneDS = api.AddNoneDataSource("none", new DataSourceOptions {
MetricsConfig = DataSourceMetricsConfig.ENABLED
});
noneDS.CreateResolver("noneResolver", new BaseResolverProps {
TypeName = "Mutation",
FieldName = "addDemoMetricsConfig",
MetricsConfig = ResolverMetricsConfig.ENABLED
});
schema := appsync.NewSchemaFile(&SchemaProps{
FilePath: jsii.String("mySchemaFile"),
})
api := appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
Name: jsii.String("myApi"),
Definition: appsync.Definition_FromSchema(schema),
EnhancedMetricsConfig: &EnhancedMetricsConfig{
DataSourceLevelMetricsBehavior: appsync.DataSourceLevelMetricsBehavior_PER_DATA_SOURCE_METRICS,
OperationLevelMetricsConfig: appsync.OperationLevelMetricsConfig_ENABLED,
ResolverLevelMetricsBehavior: appsync.ResolverLevelMetricsBehavior_PER_RESOLVER_METRICS,
},
})
noneDS := api.AddNoneDataSource(jsii.String("none"), &DataSourceOptions{
MetricsConfig: appsync.DataSourceMetricsConfig_ENABLED,
})
noneDS.CreateResolver(jsii.String("noneResolver"), &BaseResolverProps{
TypeName: jsii.String("Mutation"),
FieldName: jsii.String("addDemoMetricsConfig"),
MetricsConfig: appsync.ResolverMetricsConfig_ENABLED,
})
Events
Example
AWS AppSync Events lets you create secure and performant serverless WebSocket APIs that can broadcast real-time event data to millions of subscribers, without you having to manage connections or resource scaling.
const apiKeyProvider: appsync.AppSyncAuthProvider = {
authorizationType: appsync.AppSyncAuthorizationType.API_KEY,
};
const api = new appsync.EventApi(this, 'api', {
apiName: 'Api',
ownerContact: 'OwnerContact',
authorizationConfig: {
authProviders: [
apiKeyProvider,
],
connectionAuthModeTypes: [
appsync.AppSyncAuthorizationType.API_KEY,
],
defaultPublishAuthModeTypes: [
appsync.AppSyncAuthorizationType.API_KEY,
],
defaultSubscribeAuthModeTypes: [
appsync.AppSyncAuthorizationType.API_KEY,
],
},
});
api.addChannelNamespace('default');
api_key_provider = appsync.AppSyncAuthProvider(
authorization_type=appsync.AppSyncAuthorizationType.API_KEY
)
api = appsync.EventApi(self, "api",
api_name="Api",
owner_contact="OwnerContact",
authorization_config=appsync.EventApiAuthConfig(
auth_providers=[api_key_provider
],
connection_auth_mode_types=[appsync.AppSyncAuthorizationType.API_KEY
],
default_publish_auth_mode_types=[appsync.AppSyncAuthorizationType.API_KEY
],
default_subscribe_auth_mode_types=[appsync.AppSyncAuthorizationType.API_KEY
]
)
)
api.add_channel_namespace("default")
AppSyncAuthProvider apiKeyProvider = AppSyncAuthProvider.builder()
.authorizationType(AppSyncAuthorizationType.API_KEY)
.build();
EventApi api = EventApi.Builder.create(this, "api")
.apiName("Api")
.ownerContact("OwnerContact")
.authorizationConfig(EventApiAuthConfig.builder()
.authProviders(List.of(apiKeyProvider))
.connectionAuthModeTypes(List.of(AppSyncAuthorizationType.API_KEY))
.defaultPublishAuthModeTypes(List.of(AppSyncAuthorizationType.API_KEY))
.defaultSubscribeAuthModeTypes(List.of(AppSyncAuthorizationType.API_KEY))
.build())
.build();
api.addChannelNamespace("default");
var apiKeyProvider = new AppSyncAuthProvider {
AuthorizationType = AppSyncAuthorizationType.API_KEY
};
var api = new EventApi(this, "api", new EventApiProps {
ApiName = "Api",
OwnerContact = "OwnerContact",
AuthorizationConfig = new EventApiAuthConfig {
AuthProviders = new [] { apiKeyProvider },
ConnectionAuthModeTypes = new [] { AppSyncAuthorizationType.API_KEY },
DefaultPublishAuthModeTypes = new [] { AppSyncAuthorizationType.API_KEY },
DefaultSubscribeAuthModeTypes = new [] { AppSyncAuthorizationType.API_KEY }
}
});
api.AddChannelNamespace("default");
apiKeyProvider := &AppSyncAuthProvider{
AuthorizationType: appsync.AppSyncAuthorizationType_API_KEY,
}
api := appsync.NewEventApi(this, jsii.String("api"), &EventApiProps{
ApiName: jsii.String("Api"),
OwnerContact: jsii.String("OwnerContact"),
AuthorizationConfig: &EventApiAuthConfig{
AuthProviders: []AppSyncAuthProvider{
apiKeyProvider,
},
ConnectionAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_API_KEY,
},
DefaultPublishAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_API_KEY,
},
DefaultSubscribeAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_API_KEY,
},
},
})
api.AddChannelNamespace(jsii.String("default"))
Authorization
AWS AppSync Events offers the following authorization types to secure Event APIs: API keys, Lambda, IAM, OpenID Connect, and Amazon Cognito user pools. Each option provides a different method of security:
- API Keys (
AppSyncAuthorizationType.API_KEY) - Amazon Cognito User Pools (
AppSyncAuthorizationType.USER_POOL) - OpenID Connect (
AppSyncAuthorizationType.OIDC) - AWS Identity and Access Management (
AppSyncAuthorizationType.IAM) - AWS Lambda (
AppSyncAuthorizationType.LAMBDA)
When you define your API, you configure the authorization mode to connect to your Event API WebSocket. You also configure the default authorization modes to use when publishing and subscribing to messages. If you don't specify any authorization providers, an API key will be created for you as the authorization mode for the API.
For mor information, see Configuring authorization and authentication to secure Event APIs.
import * as lambda from 'aws-cdk-lib/aws-lambda';
declare const handler: lambda.Function;
const iamProvider: appsync.AppSyncAuthProvider = {
authorizationType: appsync.AppSyncAuthorizationType.IAM,
};
const apiKeyProvider: appsync.AppSyncAuthProvider = {
authorizationType: appsync.AppSyncAuthorizationType.API_KEY,
};
const lambdaProvider: appsync.AppSyncAuthProvider = {
authorizationType: appsync.AppSyncAuthorizationType.LAMBDA,
lambdaAuthorizerConfig: {
handler,
resultsCacheTtl: Duration.minutes(6),
validationRegex: 'test',
},
};
const api = new appsync.EventApi(this, 'api', {
apiName: 'api',
authorizationConfig: {
// set auth providers
authProviders: [
iamProvider,
apiKeyProvider,
lambdaProvider,
],
connectionAuthModeTypes: [
appsync.AppSyncAuthorizationType.IAM, // IAM authorization to connect
],
defaultPublishAuthModeTypes: [
appsync.AppSyncAuthorizationType.API_KEY, // API key authorization to publish
],
defaultSubscribeAuthModeTypes: [
appsync.AppSyncAuthorizationType.LAMBDA, // Lambda authorization to subscribe
],
}
});
api.addChannelNamespace('default');
import aws_cdk.aws_lambda as lambda_
# handler: lambda.Function
iam_provider = appsync.AppSyncAuthProvider(
authorization_type=appsync.AppSyncAuthorizationType.IAM
)
api_key_provider = appsync.AppSyncAuthProvider(
authorization_type=appsync.AppSyncAuthorizationType.API_KEY
)
lambda_provider = appsync.AppSyncAuthProvider(
authorization_type=appsync.AppSyncAuthorizationType.LAMBDA,
lambda_authorizer_config=appsync.AppSyncLambdaAuthorizerConfig(
handler=handler,
results_cache_ttl=Duration.minutes(6),
validation_regex="test"
)
)
api = appsync.EventApi(self, "api",
api_name="api",
authorization_config=appsync.EventApiAuthConfig(
# set auth providers
auth_providers=[iam_provider, api_key_provider, lambda_provider
],
connection_auth_mode_types=[appsync.AppSyncAuthorizationType.IAM
],
default_publish_auth_mode_types=[appsync.AppSyncAuthorizationType.API_KEY
],
default_subscribe_auth_mode_types=[appsync.AppSyncAuthorizationType.LAMBDA
]
)
)
api.add_channel_namespace("default")
import software.amazon.awscdk.services.lambda.*;
Function handler;
AppSyncAuthProvider iamProvider = AppSyncAuthProvider.builder()
.authorizationType(AppSyncAuthorizationType.IAM)
.build();
AppSyncAuthProvider apiKeyProvider = AppSyncAuthProvider.builder()
.authorizationType(AppSyncAuthorizationType.API_KEY)
.build();
AppSyncAuthProvider lambdaProvider = AppSyncAuthProvider.builder()
.authorizationType(AppSyncAuthorizationType.LAMBDA)
.lambdaAuthorizerConfig(AppSyncLambdaAuthorizerConfig.builder()
.handler(handler)
.resultsCacheTtl(Duration.minutes(6))
.validationRegex("test")
.build())
.build();
EventApi api = EventApi.Builder.create(this, "api")
.apiName("api")
.authorizationConfig(EventApiAuthConfig.builder()
// set auth providers
.authProviders(List.of(iamProvider, apiKeyProvider, lambdaProvider))
.connectionAuthModeTypes(List.of(AppSyncAuthorizationType.IAM))
.defaultPublishAuthModeTypes(List.of(AppSyncAuthorizationType.API_KEY))
.defaultSubscribeAuthModeTypes(List.of(AppSyncAuthorizationType.LAMBDA))
.build())
.build();
api.addChannelNamespace("default");
using Amazon.CDK.AWS.Lambda;
Function handler;
var iamProvider = new AppSyncAuthProvider {
AuthorizationType = AppSyncAuthorizationType.IAM
};
var apiKeyProvider = new AppSyncAuthProvider {
AuthorizationType = AppSyncAuthorizationType.API_KEY
};
var lambdaProvider = new AppSyncAuthProvider {
AuthorizationType = AppSyncAuthorizationType.LAMBDA,
LambdaAuthorizerConfig = new AppSyncLambdaAuthorizerConfig {
Handler = handler,
ResultsCacheTtl = Duration.Minutes(6),
ValidationRegex = "test"
}
};
var api = new EventApi(this, "api", new EventApiProps {
ApiName = "api",
AuthorizationConfig = new EventApiAuthConfig {
// set auth providers
AuthProviders = new [] { iamProvider, apiKeyProvider, lambdaProvider },
ConnectionAuthModeTypes = new [] { AppSyncAuthorizationType.IAM },
DefaultPublishAuthModeTypes = new [] { AppSyncAuthorizationType.API_KEY },
DefaultSubscribeAuthModeTypes = new [] { AppSyncAuthorizationType.LAMBDA }
}
});
api.AddChannelNamespace("default");
import lambda "github.com/aws/aws-cdk-go/awscdk"
var handler Function
iamProvider := &AppSyncAuthProvider{
AuthorizationType: appsync.AppSyncAuthorizationType_IAM,
}
apiKeyProvider := &AppSyncAuthProvider{
AuthorizationType: appsync.AppSyncAuthorizationType_API_KEY,
}
lambdaProvider := &AppSyncAuthProvider{
AuthorizationType: appsync.AppSyncAuthorizationType_LAMBDA,
LambdaAuthorizerConfig: &AppSyncLambdaAuthorizerConfig{
Handler: *Handler,
ResultsCacheTtl: awscdk.Duration_Minutes(jsii.Number(6)),
ValidationRegex: jsii.String("test"),
},
}
api := appsync.NewEventApi(this, jsii.String("api"), &EventApiProps{
ApiName: jsii.String("api"),
AuthorizationConfig: &EventApiAuthConfig{
// set auth providers
AuthProviders: []AppSyncAuthProvider{
iamProvider,
apiKeyProvider,
lambdaProvider,
},
ConnectionAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_IAM,
},
DefaultPublishAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_API_KEY,
},
DefaultSubscribeAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_LAMBDA,
},
},
})
api.AddChannelNamespace(jsii.String("default"))
If you don't specify any overrides for the connectionAuthModeTypes, defaultPublishAuthModeTypes, and defaultSubscribeAuthModeTypes parameters then all authProviders defined are included as default authorization mode types for connection, publish, and subscribe.
import * as lambda from 'aws-cdk-lib/aws-lambda';
declare const handler: lambda.Function;
const iamProvider: appsync.AppSyncAuthProvider = {
authorizationType: appsync.AppSyncAuthorizationType.IAM,
};
const apiKeyProvider: appsync.AppSyncAuthProvider = {
authorizationType: appsync.AppSyncAuthorizationType.API_KEY,
};
/* API with IAM and API Key providers.
* Connection, default publish and default subscribe
* can be done with either IAM and API Key.
*/
const api = new appsync.EventApi(this, 'api', {
apiName: 'api',
authorizationConfig: {
// set auth providers
authProviders: [
iamProvider,
apiKeyProvider,
],
}
});
api.addChannelNamespace('default');
import aws_cdk.aws_lambda as lambda_
# handler: lambda.Function
iam_provider = appsync.AppSyncAuthProvider(
authorization_type=appsync.AppSyncAuthorizationType.IAM
)
api_key_provider = appsync.AppSyncAuthProvider(
authorization_type=appsync.AppSyncAuthorizationType.API_KEY
)
# API with IAM and API Key providers.
# Connection, default publish and default subscribe
# can be done with either IAM and API Key.
#
api = appsync.EventApi(self, "api",
api_name="api",
authorization_config=appsync.EventApiAuthConfig(
# set auth providers
auth_providers=[iam_provider, api_key_provider
]
)
)
api.add_channel_namespace("default")
import software.amazon.awscdk.services.lambda.*;
Function handler;
AppSyncAuthProvider iamProvider = AppSyncAuthProvider.builder()
.authorizationType(AppSyncAuthorizationType.IAM)
.build();
AppSyncAuthProvider apiKeyProvider = AppSyncAuthProvider.builder()
.authorizationType(AppSyncAuthorizationType.API_KEY)
.build();
/* API with IAM and API Key providers.
* Connection, default publish and default subscribe
* can be done with either IAM and API Key.
*/
EventApi api = EventApi.Builder.create(this, "api")
.apiName("api")
.authorizationConfig(EventApiAuthConfig.builder()
// set auth providers
.authProviders(List.of(iamProvider, apiKeyProvider))
.build())
.build();
api.addChannelNamespace("default");
using Amazon.CDK.AWS.Lambda;
Function handler;
var iamProvider = new AppSyncAuthProvider {
AuthorizationType = AppSyncAuthorizationType.IAM
};
var apiKeyProvider = new AppSyncAuthProvider {
AuthorizationType = AppSyncAuthorizationType.API_KEY
};
/* API with IAM and API Key providers.
* Connection, default publish and default subscribe
* can be done with either IAM and API Key.
*/
var api = new EventApi(this, "api", new EventApiProps {
ApiName = "api",
AuthorizationConfig = new EventApiAuthConfig {
// set auth providers
AuthProviders = new [] { iamProvider, apiKeyProvider }
}
});
api.AddChannelNamespace("default");
import lambda "github.com/aws/aws-cdk-go/awscdk"
var handler Function
iamProvider := &AppSyncAuthProvider{
AuthorizationType: appsync.AppSyncAuthorizationType_IAM,
}
apiKeyProvider := &AppSyncAuthProvider{
AuthorizationType: appsync.AppSyncAuthorizationType_API_KEY,
}
/* API with IAM and API Key providers.
* Connection, default publish and default subscribe
* can be done with either IAM and API Key.
*/
api := appsync.NewEventApi(this, jsii.String("api"), &EventApiProps{
ApiName: jsii.String("api"),
AuthorizationConfig: &EventApiAuthConfig{
// set auth providers
AuthProviders: []AppSyncAuthProvider{
iamProvider,
apiKeyProvider,
},
},
})
api.AddChannelNamespace(jsii.String("default"))
Data Sources
With AWS AppSync Events, you can configure data source integrations with Amazon DynamoDB, Amazon Aurora Serverless, Amazon EventBridge, Amazon Bedrock Runtime, AWS Lambda, Amazon OpenSearch Service, and HTTP endpoints. The Event API can be associated with the data source and you can use the data source as an integration in your channel namespace event handlers for onPublish and onSubscribe operations.
Below are examples for how you add the various data sources to you Event API.
Amazon DynamoDB
const api = new appsync.EventApi(this, 'EventApiDynamoDB', {
apiName: 'DynamoDBEventApi',
});
const table = new dynamodb.Table(this, 'table', {
tableName: 'event-messages',
partitionKey: {
name: 'id',
type: dynamodb.AttributeType.STRING,
},
});
const dataSource = api.addDynamoDbDataSource('ddbsource', table);
api = appsync.EventApi(self, "EventApiDynamoDB",
api_name="DynamoDBEventApi"
)
table = dynamodb.Table(self, "table",
table_name="event-messages",
partition_key=dynamodb.Attribute(
name="id",
type=dynamodb.AttributeType.STRING
)
)
data_source = api.add_dynamo_db_data_source("ddbsource", table)
EventApi api = EventApi.Builder.create(this, "EventApiDynamoDB")
.apiName("DynamoDBEventApi")
.build();
Table table = Table.Builder.create(this, "table")
.tableName("event-messages")
.partitionKey(Attribute.builder()
.name("id")
.type(AttributeType.STRING)
.build())
.build();
AppSyncDynamoDbDataSource dataSource = api.addDynamoDbDataSource("ddbsource", table);
var api = new EventApi(this, "EventApiDynamoDB", new EventApiProps {
ApiName = "DynamoDBEventApi"
});
var table = new Table(this, "table", new TableProps {
TableName = "event-messages",
PartitionKey = new Attribute {
Name = "id",
Type = AttributeType.STRING
}
});
var dataSource = api.AddDynamoDbDataSource("ddbsource", table);
api := appsync.NewEventApi(this, jsii.String("EventApiDynamoDB"), &EventApiProps{
ApiName: jsii.String("DynamoDBEventApi"),
})
table := dynamodb.NewTable(this, jsii.String("table"), &TableProps{
TableName: jsii.String("event-messages"),
PartitionKey: &Attribute{
Name: jsii.String("id"),
Type: dynamodb.AttributeType_STRING,
},
})
dataSource := api.AddDynamoDbDataSource(jsii.String("ddbsource"), table)
Amazon Aurora Serverless
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
declare const vpc: ec2.Vpc;
const databaseName = 'mydb';
const cluster = new rds.DatabaseCluster(this, 'Cluster', {
engine: rds.DatabaseClusterEngine.auroraPostgres({ version: rds.AuroraPostgresEngineVersion.VER_16_6 }),
writer: rds.ClusterInstance.serverlessV2('writer'),
vpc: vpc,
credentials: { username: 'clusteradmin' },
defaultDatabaseName: databaseName,
enableDataApi: true,
});
const secret = secretsmanager.Secret.fromSecretNameV2(this, 'Secret', 'db-secretName');
const api = new appsync.EventApi(this, 'EventApiRds', {
apiName: 'RdsEventApi',
});
const dataSource = api.addRdsDataSource('rdsds', cluster, secret, databaseName);
import aws_cdk.aws_secretsmanager as secretsmanager
# vpc: ec2.Vpc
database_name = "mydb"
cluster = rds.DatabaseCluster(self, "Cluster",
engine=rds.DatabaseClusterEngine.aurora_postgres(version=rds.AuroraPostgresEngineVersion.VER_16_6),
writer=rds.ClusterInstance.serverless_v2("writer"),
vpc=vpc,
credentials={"username": "clusteradmin"},
default_database_name=database_name,
enable_data_api=True
)
secret = secretsmanager.Secret.from_secret_name_v2(self, "Secret", "db-secretName")
api = appsync.EventApi(self, "EventApiRds",
api_name="RdsEventApi"
)
data_source = api.add_rds_data_source("rdsds", cluster, secret, database_name)
import software.amazon.awscdk.services.secretsmanager.*;
Vpc vpc;
String databaseName = "mydb";
DatabaseCluster cluster = DatabaseCluster.Builder.create(this, "Cluster")
.engine(DatabaseClusterEngine.auroraPostgres(AuroraPostgresClusterEngineProps.builder().version(AuroraPostgresEngineVersion.VER_16_6).build()))
.writer(ClusterInstance.serverlessV2("writer"))
.vpc(vpc)
.credentials(Map.of("username", "clusteradmin"))
.defaultDatabaseName(databaseName)
.enableDataApi(true)
.build();
ISecret secret = Secret.fromSecretNameV2(this, "Secret", "db-secretName");
EventApi api = EventApi.Builder.create(this, "EventApiRds")
.apiName("RdsEventApi")
.build();
AppSyncRdsDataSource dataSource = api.addRdsDataSource("rdsds", cluster, secret, databaseName);
using Amazon.CDK.AWS.SecretsManager;
Vpc vpc;
var databaseName = "mydb";
var cluster = new DatabaseCluster(this, "Cluster", new DatabaseClusterProps {
Engine = DatabaseClusterEngine.AuroraPostgres(new AuroraPostgresClusterEngineProps { Version = AuroraPostgresEngineVersion.VER_16_6 }),
Writer = ClusterInstance.ServerlessV2("writer"),
Vpc = vpc,
Credentials = new Dictionary<string, string> { { "username", "clusteradmin" } },
DefaultDatabaseName = databaseName,
EnableDataApi = true
});
var secret = Secret.FromSecretNameV2(this, "Secret", "db-secretName");
var api = new EventApi(this, "EventApiRds", new EventApiProps {
ApiName = "RdsEventApi"
});
var dataSource = api.AddRdsDataSource("rdsds", cluster, secret, databaseName);
import secretsmanager "github.com/aws/aws-cdk-go/awscdk"
var vpc Vpc
databaseName := "mydb"
cluster := rds.NewDatabaseCluster(this, jsii.String("Cluster"), &DatabaseClusterProps{
Engine: rds.DatabaseClusterEngine_AuroraPostgres(&AuroraPostgresClusterEngineProps{
Version: rds.AuroraPostgresEngineVersion_VER_16_6(),
}),
Writer: rds.ClusterInstance_ServerlessV2(jsii.String("writer")),
Vpc: vpc,
Credentials: map[string]*string{
"username": jsii.String("clusteradmin"),
},
DefaultDatabaseName: databaseName,
EnableDataApi: jsii.Boolean(true),
})
secret := secretsmanager.Secret_FromSecretNameV2(this, jsii.String("Secret"), jsii.String("db-secretName"))
api := appsync.NewEventApi(this, jsii.String("EventApiRds"), &EventApiProps{
ApiName: jsii.String("RdsEventApi"),
})
dataSource := api.AddRdsDataSource(jsii.String("rdsds"), cluster, secret, databaseName)
Amazon EventBridge
import * as events from 'aws-cdk-lib/aws-events';
const api = new appsync.EventApi(this, 'EventApiEventBridge', {
apiName: 'EventBridgeEventApi',
});
const eventBus = new events.EventBus(this, 'test-bus');
const dataSource = api.addEventBridgeDataSource('eventbridgeds', eventBus);
import aws_cdk.aws_events as events
api = appsync.EventApi(self, "EventApiEventBridge",
api_name="EventBridgeEventApi"
)
event_bus = events.EventBus(self, "test-bus")
data_source = api.add_event_bridge_data_source("eventbridgeds", event_bus)
import software.amazon.awscdk.services.events.*;
EventApi api = EventApi.Builder.create(this, "EventApiEventBridge")
.apiName("EventBridgeEventApi")
.build();
EventBus eventBus = new EventBus(this, "test-bus");
AppSyncEventBridgeDataSource dataSource = api.addEventBridgeDataSource("eventbridgeds", eventBus);
using Amazon.CDK.AWS.Events;
var api = new EventApi(this, "EventApiEventBridge", new EventApiProps {
ApiName = "EventBridgeEventApi"
});
var eventBus = new EventBus(this, "test-bus");
var dataSource = api.AddEventBridgeDataSource("eventbridgeds", eventBus);
import events "github.com/aws/aws-cdk-go/awscdk"
api := appsync.NewEventApi(this, jsii.String("EventApiEventBridge"), &EventApiProps{
ApiName: jsii.String("EventBridgeEventApi"),
})
eventBus := events.NewEventBus(this, jsii.String("test-bus"))
dataSource := api.AddEventBridgeDataSource(jsii.String("eventbridgeds"), eventBus)
AWS Lambda
import * as lambda from 'aws-cdk-lib/aws-lambda';
declare const lambdaDs: lambda.Function;
const api = new appsync.EventApi(this, 'EventApiLambda', {
apiName: 'LambdaEventApi',
});
const dataSource = api.addLambdaDataSource('lambdads', lambdaDs);
import aws_cdk.aws_lambda as lambda_
# lambda_ds: lambda.Function
api = appsync.EventApi(self, "EventApiLambda",
api_name="LambdaEventApi"
)
data_source = api.add_lambda_data_source("lambdads", lambda_ds)
import software.amazon.awscdk.services.lambda.*;
Function lambdaDs;
EventApi api = EventApi.Builder.create(this, "EventApiLambda")
.apiName("LambdaEventApi")
.build();
AppSyncLambdaDataSource dataSource = api.addLambdaDataSource("lambdads", lambdaDs);
using Amazon.CDK.AWS.Lambda;
Function lambdaDs;
var api = new EventApi(this, "EventApiLambda", new EventApiProps {
ApiName = "LambdaEventApi"
});
var dataSource = api.AddLambdaDataSource("lambdads", lambdaDs);
import lambda "github.com/aws/aws-cdk-go/awscdk"
var lambdaDs Function
api := appsync.NewEventApi(this, jsii.String("EventApiLambda"), &EventApiProps{
ApiName: jsii.String("LambdaEventApi"),
})
dataSource := api.AddLambdaDataSource(jsii.String("lambdads"), lambdaDs)
Amazon OpenSearch Service
import * as opensearch from 'aws-cdk-lib/aws-opensearchservice';
const domain = new opensearch.Domain(this, 'Domain', {
version: opensearch.EngineVersion.OPENSEARCH_2_17,
encryptionAtRest: {
enabled: true,
},
nodeToNodeEncryption: true,
enforceHttps: true,
capacity: {
multiAzWithStandbyEnabled: false,
},
ebs: {
enabled: true,
volumeSize: 10,
},
});
const api = new appsync.EventApi(this, 'EventApiOpenSearch', {
apiName: 'OpenSearchEventApi',
});
const dataSource = api.addOpenSearchDataSource('opensearchds', domain);
import aws_cdk.aws_opensearchservice as opensearch
domain = opensearch.Domain(self, "Domain",
version=opensearch.EngineVersion.OPENSEARCH_2_17,
encryption_at_rest=opensearch.EncryptionAtRestOptions(
enabled=True
),
node_to_node_encryption=True,
enforce_https=True,
capacity=opensearch.CapacityConfig(
multi_az_with_standby_enabled=False
),
ebs=opensearch.EbsOptions(
enabled=True,
volume_size=10
)
)
api = appsync.EventApi(self, "EventApiOpenSearch",
api_name="OpenSearchEventApi"
)
data_source = api.add_open_search_data_source("opensearchds", domain)
import software.amazon.awscdk.services.opensearchservice.*;
Domain domain = Domain.Builder.create(this, "Domain")
.version(EngineVersion.OPENSEARCH_2_17)
.encryptionAtRest(EncryptionAtRestOptions.builder()
.enabled(true)
.build())
.nodeToNodeEncryption(true)
.enforceHttps(true)
.capacity(CapacityConfig.builder()
.multiAzWithStandbyEnabled(false)
.build())
.ebs(EbsOptions.builder()
.enabled(true)
.volumeSize(10)
.build())
.build();
EventApi api = EventApi.Builder.create(this, "EventApiOpenSearch")
.apiName("OpenSearchEventApi")
.build();
AppSyncOpenSearchDataSource dataSource = api.addOpenSearchDataSource("opensearchds", domain);
using Amazon.CDK.AWS.OpenSearchService;
var domain = new Domain(this, "Domain", new DomainProps {
Version = EngineVersion.OPENSEARCH_2_17,
EncryptionAtRest = new EncryptionAtRestOptions {
Enabled = true
},
NodeToNodeEncryption = true,
EnforceHttps = true,
Capacity = new CapacityConfig {
MultiAzWithStandbyEnabled = false
},
Ebs = new EbsOptions {
Enabled = true,
VolumeSize = 10
}
});
var api = new EventApi(this, "EventApiOpenSearch", new EventApiProps {
ApiName = "OpenSearchEventApi"
});
var dataSource = api.AddOpenSearchDataSource("opensearchds", domain);
import "github.com/aws/aws-cdk-go/awscdk"
domain := opensearch.NewDomain(this, jsii.String("Domain"), &DomainProps{
Version: opensearch.EngineVersion_OPENSEARCH_2_17(),
EncryptionAtRest: &EncryptionAtRestOptions{
Enabled: jsii.Boolean(true),
},
NodeToNodeEncryption: jsii.Boolean(true),
EnforceHttps: jsii.Boolean(true),
Capacity: &CapacityConfig{
MultiAzWithStandbyEnabled: jsii.Boolean(false),
},
Ebs: &EbsOptions{
Enabled: jsii.Boolean(true),
VolumeSize: jsii.Number(10),
},
})
api := appsync.NewEventApi(this, jsii.String("EventApiOpenSearch"), &EventApiProps{
ApiName: jsii.String("OpenSearchEventApi"),
})
dataSource := api.AddOpenSearchDataSource(jsii.String("opensearchds"), domain)
HTTP Endpoints
import * as apigw from 'aws-cdk-lib/aws-apigateway';
const api = new appsync.EventApi(this, 'EventApiHttp', {
apiName: 'HttpEventApi',
});
const randomApi = new apigw.RestApi(this, 'RandomApi');
const randomRoute = randomApi.root.addResource('random');
randomRoute.addMethod('GET', new apigw.MockIntegration({
integrationResponses: [{
statusCode: '200',
responseTemplates: {
'application/json': 'my-random-value',
},
}],
passthroughBehavior: apigw.PassthroughBehavior.NEVER,
requestTemplates: {
'application/json': '{ "statusCode": 200 }',
},
}), {
methodResponses: [{ statusCode: '200' }],
});
const dataSource = api.addHttpDataSource('httpsource', `https://${randomApi.restApiId}.execute-api.${this.region}.amazonaws.com`);
import aws_cdk.aws_apigateway as apigw
api = appsync.EventApi(self, "EventApiHttp",
api_name="HttpEventApi"
)
random_api = apigw.RestApi(self, "RandomApi")
random_route = random_api.root.add_resource("random")
random_route.add_method("GET", apigw.MockIntegration(
integration_responses=[apigw.IntegrationResponse(
status_code="200",
response_templates={
"application/json": "my-random-value"
}
)],
passthrough_behavior=apigw.PassthroughBehavior.NEVER,
request_templates={
"application/json": "{ \"statusCode\": 200 }"
}
),
method_responses=[apigw.MethodResponse(status_code="200")]
)
data_source = api.add_http_data_source("httpsource", f"https://{randomApi.restApiId}.execute-api.{this.region}.amazonaws.com")
import software.amazon.awscdk.services.apigateway.*;
EventApi api = EventApi.Builder.create(this, "EventApiHttp")
.apiName("HttpEventApi")
.build();
RestApi randomApi = new RestApi(this, "RandomApi");
Resource randomRoute = randomApi.root.addResource("random");
randomRoute.addMethod("GET", MockIntegration.Builder.create()
.integrationResponses(List.of(IntegrationResponse.builder()
.statusCode("200")
.responseTemplates(Map.of(
"application/json", "my-random-value"))
.build()))
.passthroughBehavior(PassthroughBehavior.NEVER)
.requestTemplates(Map.of(
"application/json", "{ \"statusCode\": 200 }"))
.build(), MethodOptions.builder()
.methodResponses(List.of(MethodResponse.builder().statusCode("200").build()))
.build());
AppSyncHttpDataSource dataSource = api.addHttpDataSource("httpsource", String.format("https://%s.execute-api.%s.amazonaws.com", randomApi.getRestApiId(), this.region));
using Amazon.CDK.AWS.APIGateway;
var api = new EventApi(this, "EventApiHttp", new EventApiProps {
ApiName = "HttpEventApi"
});
var randomApi = new RestApi(this, "RandomApi");
var randomRoute = randomApi.Root.AddResource("random");
randomRoute.AddMethod("GET", new MockIntegration(new IntegrationOptions {
IntegrationResponses = new [] { new IntegrationResponse {
StatusCode = "200",
ResponseTemplates = new Dictionary<string, string> {
{ "application/json", "my-random-value" }
}
} },
PassthroughBehavior = PassthroughBehavior.NEVER,
RequestTemplates = new Dictionary<string, string> {
{ "application/json", "{ \"statusCode\": 200 }" }
}
}), new MethodOptions {
MethodResponses = new [] { new MethodResponse { StatusCode = "200" } }
});
var dataSource = api.AddHttpDataSource("httpsource", $"https://{randomApi.restApiId}.execute-api.{this.region}.amazonaws.com");
import "github.com/aws/aws-cdk-go/awscdk"
api := appsync.NewEventApi(this, jsii.String("EventApiHttp"), &EventApiProps{
ApiName: jsii.String("HttpEventApi"),
})
randomApi := apigw.NewRestApi(this, jsii.String("RandomApi"))
randomRoute := randomApi.Root.AddResource(jsii.String("random"))
randomRoute.AddMethod(jsii.String("GET"), apigw.NewMockIntegration(&IntegrationOptions{
IntegrationResponses: []IntegrationResponse{
&IntegrationResponse{
StatusCode: jsii.String("200"),
ResponseTemplates: map[string]*string{
"application/json": jsii.String("my-random-value"),
},
},
},
PassthroughBehavior: apigw.PassthroughBehavior_NEVER,
RequestTemplates: map[string]*string{
"application/json": jsii.String("{ \"statusCode\": 200 }"),
},
}), &MethodOptions{
MethodResponses: []MethodResponse{
&MethodResponse{
StatusCode: jsii.String("200"),
},
},
})
dataSource := api.AddHttpDataSource(jsii.String("httpsource"), fmt.Sprintf("https://%v.execute-api.%v.amazonaws.com", randomApi.RestApiId, this.Region))
Custom Domain Names
With AWS AppSync, you can use custom domain names to configure a single, memorable domain that works for your Event APIs. You can set custom domain by setting domainName. Also you can get custom HTTP/Realtime endpoint by customHttpEndpoint, customRealtimeEndpoint.
For more information, see Configuring custom domain names for Event APIs.
import * as acm from 'aws-cdk-lib/aws-certificatemanager';
import * as route53 from 'aws-cdk-lib/aws-route53';
const myDomainName = 'api.example.com';
const certificate = new acm.Certificate(this, 'cert', { domainName: myDomainName });
const apiKeyProvider: appsync.AppSyncAuthProvider = {
authorizationType: appsync.AppSyncAuthorizationType.API_KEY,
};
const api = new appsync.EventApi(this, 'api', {
apiName: 'Api',
ownerContact: 'OwnerContact',
authorizationConfig: {
authProviders: [
apiKeyProvider,
],
connectionAuthModeTypes: [
appsync.AppSyncAuthorizationType.API_KEY,
],
defaultPublishAuthModeTypes: [
appsync.AppSyncAuthorizationType.API_KEY,
],
defaultSubscribeAuthModeTypes: [
appsync.AppSyncAuthorizationType.API_KEY,
],
},
// Custom Domain Settings
domainName: {
certificate,
domainName: myDomainName,
},
});
api.addChannelNamespace('default');
// You can get custom HTTP/Realtime endpoint
new CfnOutput(this, 'AWS AppSync Events HTTP endpoint', { value: api.customHttpEndpoint });
new CfnOutput(this, 'AWS AppSync Events Realtime endpoint', { value: api.customRealtimeEndpoint });
import aws_cdk.aws_certificatemanager as acm
import aws_cdk.aws_route53 as route53
my_domain_name = "api.example.com"
certificate = acm.Certificate(self, "cert", domain_name=my_domain_name)
api_key_provider = appsync.AppSyncAuthProvider(
authorization_type=appsync.AppSyncAuthorizationType.API_KEY
)
api = appsync.EventApi(self, "api",
api_name="Api",
owner_contact="OwnerContact",
authorization_config=appsync.EventApiAuthConfig(
auth_providers=[api_key_provider
],
connection_auth_mode_types=[appsync.AppSyncAuthorizationType.API_KEY
],
default_publish_auth_mode_types=[appsync.AppSyncAuthorizationType.API_KEY
],
default_subscribe_auth_mode_types=[appsync.AppSyncAuthorizationType.API_KEY
]
),
# Custom Domain Settings
domain_name=appsync.AppSyncDomainOptions(
certificate=certificate,
domain_name=my_domain_name
)
)
api.add_channel_namespace("default")
# You can get custom HTTP/Realtime endpoint
CfnOutput(self, "AWS AppSync Events HTTP endpoint", value=api.custom_http_endpoint)
CfnOutput(self, "AWS AppSync Events Realtime endpoint", value=api.custom_realtime_endpoint)
import software.amazon.awscdk.services.certificatemanager.*;
import software.amazon.awscdk.services.route53.*;
String myDomainName = "api.example.com";
Certificate certificate = Certificate.Builder.create(this, "cert").domainName(myDomainName).build();
AppSyncAuthProvider apiKeyProvider = AppSyncAuthProvider.builder()
.authorizationType(AppSyncAuthorizationType.API_KEY)
.build();
EventApi api = EventApi.Builder.create(this, "api")
.apiName("Api")
.ownerContact("OwnerContact")
.authorizationConfig(EventApiAuthConfig.builder()
.authProviders(List.of(apiKeyProvider))
.connectionAuthModeTypes(List.of(AppSyncAuthorizationType.API_KEY))
.defaultPublishAuthModeTypes(List.of(AppSyncAuthorizationType.API_KEY))
.defaultSubscribeAuthModeTypes(List.of(AppSyncAuthorizationType.API_KEY))
.build())
// Custom Domain Settings
.domainName(AppSyncDomainOptions.builder()
.certificate(certificate)
.domainName(myDomainName)
.build())
.build();
api.addChannelNamespace("default");
// You can get custom HTTP/Realtime endpoint
// You can get custom HTTP/Realtime endpoint
CfnOutput.Builder.create(this, "AWS AppSync Events HTTP endpoint").value(api.getCustomHttpEndpoint()).build();
CfnOutput.Builder.create(this, "AWS AppSync Events Realtime endpoint").value(api.getCustomRealtimeEndpoint()).build();
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.Route53;
var myDomainName = "api.example.com";
var certificate = new Certificate(this, "cert", new CertificateProps { DomainName = myDomainName });
var apiKeyProvider = new AppSyncAuthProvider {
AuthorizationType = AppSyncAuthorizationType.API_KEY
};
var api = new EventApi(this, "api", new EventApiProps {
ApiName = "Api",
OwnerContact = "OwnerContact",
AuthorizationConfig = new EventApiAuthConfig {
AuthProviders = new [] { apiKeyProvider },
ConnectionAuthModeTypes = new [] { AppSyncAuthorizationType.API_KEY },
DefaultPublishAuthModeTypes = new [] { AppSyncAuthorizationType.API_KEY },
DefaultSubscribeAuthModeTypes = new [] { AppSyncAuthorizationType.API_KEY }
},
// Custom Domain Settings
DomainName = new AppSyncDomainOptions {
Certificate = certificate,
DomainName = myDomainName
}
});
api.AddChannelNamespace("default");
// You can get custom HTTP/Realtime endpoint
// You can get custom HTTP/Realtime endpoint
new CfnOutput(this, "AWS AppSync Events HTTP endpoint", new CfnOutputProps { Value = api.CustomHttpEndpoint });
new CfnOutput(this, "AWS AppSync Events Realtime endpoint", new CfnOutputProps { Value = api.CustomRealtimeEndpoint });
import acm "github.com/aws/aws-cdk-go/awscdk"
import route53 "github.com/aws/aws-cdk-go/awscdk"
myDomainName := "api.example.com"
certificate := acm.NewCertificate(this, jsii.String("cert"), &CertificateProps{
DomainName: myDomainName,
})
apiKeyProvider := &AppSyncAuthProvider{
AuthorizationType: appsync.AppSyncAuthorizationType_API_KEY,
}
api := appsync.NewEventApi(this, jsii.String("api"), &EventApiProps{
ApiName: jsii.String("Api"),
OwnerContact: jsii.String("OwnerContact"),
AuthorizationConfig: &EventApiAuthConfig{
AuthProviders: []AppSyncAuthProvider{
apiKeyProvider,
},
ConnectionAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_API_KEY,
},
DefaultPublishAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_API_KEY,
},
DefaultSubscribeAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_API_KEY,
},
},
// Custom Domain Settings
DomainName: &AppSyncDomainOptions{
Certificate: *Certificate,
DomainName: myDomainName,
},
})
api.AddChannelNamespace(jsii.String("default"))
// You can get custom HTTP/Realtime endpoint
// You can get custom HTTP/Realtime endpoint
awscdk.NewCfnOutput(this, jsii.String("AWS AppSync Events HTTP endpoint"), &CfnOutputProps{
Value: api.customHttpEndpoint,
})
awscdk.NewCfnOutput(this, jsii.String("AWS AppSync Events Realtime endpoint"), &CfnOutputProps{
Value: api.customRealtimeEndpoint,
})
Log Group
AppSync automatically create a log group with the name /aws/appsync/apis/<api_id> upon deployment with log data set to never expire. If you want to set a different expiration period, use the logConfig.retention property.
Also you can choose the log level by setting the logConfig.fieldLogLevel property.
For more information, see Configuring CloudWatch Logs on Event APIs.
To obtain the Event API's log group as a logs.ILogGroup use the logGroup property of the Api construct.
import * as logs from 'aws-cdk-lib/aws-logs';
const apiKeyProvider: appsync.AppSyncAuthProvider = {
authorizationType: appsync.AppSyncAuthorizationType.API_KEY,
};
const api = new appsync.EventApi(this, 'api', {
apiName: 'Api',
ownerContact: 'OwnerContact',
authorizationConfig: {
authProviders: [
apiKeyProvider,
],
connectionAuthModeTypes: [
appsync.AppSyncAuthorizationType.API_KEY,
],
defaultPublishAuthModeTypes: [
appsync.AppSyncAuthorizationType.API_KEY,
],
defaultSubscribeAuthModeTypes: [
appsync.AppSyncAuthorizationType.API_KEY,
],
},
logConfig: {
fieldLogLevel: appsync.AppSyncFieldLogLevel.INFO,
retention: logs.RetentionDays.ONE_WEEK,
},
});
api.addChannelNamespace('default');
import aws_cdk.aws_logs as logs
api_key_provider = appsync.AppSyncAuthProvider(
authorization_type=appsync.AppSyncAuthorizationType.API_KEY
)
api = appsync.EventApi(self, "api",
api_name="Api",
owner_contact="OwnerContact",
authorization_config=appsync.EventApiAuthConfig(
auth_providers=[api_key_provider
],
connection_auth_mode_types=[appsync.AppSyncAuthorizationType.API_KEY
],
default_publish_auth_mode_types=[appsync.AppSyncAuthorizationType.API_KEY
],
default_subscribe_auth_mode_types=[appsync.AppSyncAuthorizationType.API_KEY
]
),
log_config=appsync.AppSyncLogConfig(
field_log_level=appsync.AppSyncFieldLogLevel.INFO,
retention=logs.RetentionDays.ONE_WEEK
)
)
api.add_channel_namespace("default")
import software.amazon.awscdk.services.logs.*;
AppSyncAuthProvider apiKeyProvider = AppSyncAuthProvider.builder()
.authorizationType(AppSyncAuthorizationType.API_KEY)
.build();
EventApi api = EventApi.Builder.create(this, "api")
.apiName("Api")
.ownerContact("OwnerContact")
.authorizationConfig(EventApiAuthConfig.builder()
.authProviders(List.of(apiKeyProvider))
.connectionAuthModeTypes(List.of(AppSyncAuthorizationType.API_KEY))
.defaultPublishAuthModeTypes(List.of(AppSyncAuthorizationType.API_KEY))
.defaultSubscribeAuthModeTypes(List.of(AppSyncAuthorizationType.API_KEY))
.build())
.logConfig(AppSyncLogConfig.builder()
.fieldLogLevel(AppSyncFieldLogLevel.INFO)
.retention(RetentionDays.ONE_WEEK)
.build())
.build();
api.addChannelNamespace("default");
using Amazon.CDK.AWS.Logs;
var apiKeyProvider = new AppSyncAuthProvider {
AuthorizationType = AppSyncAuthorizationType.API_KEY
};
var api = new EventApi(this, "api", new EventApiProps {
ApiName = "Api",
OwnerContact = "OwnerContact",
AuthorizationConfig = new EventApiAuthConfig {
AuthProviders = new [] { apiKeyProvider },
ConnectionAuthModeTypes = new [] { AppSyncAuthorizationType.API_KEY },
DefaultPublishAuthModeTypes = new [] { AppSyncAuthorizationType.API_KEY },
DefaultSubscribeAuthModeTypes = new [] { AppSyncAuthorizationType.API_KEY }
},
LogConfig = new AppSyncLogConfig {
FieldLogLevel = AppSyncFieldLogLevel.INFO,
Retention = RetentionDays.ONE_WEEK
}
});
api.AddChannelNamespace("default");
import logs "github.com/aws/aws-cdk-go/awscdk"
apiKeyProvider := &AppSyncAuthProvider{
AuthorizationType: appsync.AppSyncAuthorizationType_API_KEY,
}
api := appsync.NewEventApi(this, jsii.String("api"), &EventApiProps{
ApiName: jsii.String("Api"),
OwnerContact: jsii.String("OwnerContact"),
AuthorizationConfig: &EventApiAuthConfig{
AuthProviders: []AppSyncAuthProvider{
apiKeyProvider,
},
ConnectionAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_API_KEY,
},
DefaultPublishAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_API_KEY,
},
DefaultSubscribeAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_API_KEY,
},
},
LogConfig: &AppSyncLogConfig{
FieldLogLevel: appsync.AppSyncFieldLogLevel_INFO,
Retention: logs.RetentionDays_ONE_WEEK,
},
})
api.AddChannelNamespace(jsii.String("default"))
WAF Protection
You can use AWS WAF to protect your AppSync API from common web exploits, such as SQL injection and cross-site scripting (XSS) attacks. These could affect API availability and performance, compromise security, or consume excessive resources.
For more information, see Using AWS WAF to protect AWS AppSync Event APIs.
declare const api: appsync.EventApi;
declare const webAcl: wafv2.CfnWebACL;
// Associate waf with Event API
new wafv2.CfnWebACLAssociation(this, 'WafAssociation', {
resourceArn: api.apiArn,
webAclArn: webAcl.attrArn,
});
# api: appsync.EventApi
# web_acl: wafv2.CfnWebACL
# Associate waf with Event API
wafv2.CfnWebACLAssociation(self, "WafAssociation",
resource_arn=api.api_arn,
web_acl_arn=web_acl.attr_arn
)
EventApi api;
CfnWebACL webAcl;
// Associate waf with Event API
// Associate waf with Event API
CfnWebACLAssociation.Builder.create(this, "WafAssociation")
.resourceArn(api.getApiArn())
.webAclArn(webAcl.getAttrArn())
.build();
EventApi api;
CfnWebACL webAcl;
// Associate waf with Event API
// Associate waf with Event API
new CfnWebACLAssociation(this, "WafAssociation", new CfnWebACLAssociationProps {
ResourceArn = api.ApiArn,
WebAclArn = webAcl.AttrArn
});
var api EventApi
var webAcl CfnWebACL
// Associate waf with Event API
// Associate waf with Event API
wafv2.NewCfnWebACLAssociation(this, jsii.String("WafAssociation"), &CfnWebACLAssociationProps{
ResourceArn: api.ApiArn,
WebAclArn: webAcl.attrArn,
})
Channel namespaces
Channel namespaces define the channels that are available on your Event API, and the capabilities and behaviors of these channels. Channel namespaces provide a scalable approach to managing large numbers of channels.
Instead of configuring each channel individually, developers can apply settings across an entire namespace.
Channel namespace can optionally interact with data sources configured on the Event API by defining optional event handler code or using direct integrations with the data source where applicable.
For more information, see Understanding channel namespaces.
declare const api: appsync.EventApi;
// create a channel namespace
new appsync.ChannelNamespace(this, 'Namespace', {
api,
});
// You can also create a namespace through the addChannelNamespace method
api.addChannelNamespace('AnotherNameSpace', {});
# api: appsync.EventApi
# create a channel namespace
appsync.ChannelNamespace(self, "Namespace",
api=api
)
# You can also create a namespace through the addChannelNamespace method
api.add_channel_namespace("AnotherNameSpace")
EventApi api;
// create a channel namespace
// create a channel namespace
ChannelNamespace.Builder.create(this, "Namespace")
.api(api)
.build();
// You can also create a namespace through the addChannelNamespace method
api.addChannelNamespace("AnotherNameSpace", ChannelNamespaceOptions.builder().build());
EventApi api;
// create a channel namespace
// create a channel namespace
new ChannelNamespace(this, "Namespace", new ChannelNamespaceProps {
Api = api
});
// You can also create a namespace through the addChannelNamespace method
api.AddChannelNamespace("AnotherNameSpace", new ChannelNamespaceOptions { });
var api EventApi
// create a channel namespace
// create a channel namespace
appsync.NewChannelNamespace(this, jsii.String("Namespace"), &ChannelNamespaceProps{
Api: Api,
})
// You can also create a namespace through the addChannelNamespace method
api.AddChannelNamespace(jsii.String("AnotherNameSpace"), &ChannelNamespaceOptions{
})
The API's publishing and subscribing authorization configuration is automatically applied to all namespaces. You can override this configuration at the namespace level. Note: the authorization type you select for a namespace must be defined as an authorization provider at the API level.
declare const api: appsync.EventApi;
new appsync.ChannelNamespace(this, 'Namespace', {
api,
authorizationConfig: {
// Override publishing authorization to API Key
publishAuthModeTypes: [appsync.AppSyncAuthorizationType.API_KEY],
// Override subscribing authorization to Lambda
subscribeAuthModeTypes: [appsync.AppSyncAuthorizationType.LAMBDA],
},
});
# api: appsync.EventApi
appsync.ChannelNamespace(self, "Namespace",
api=api,
authorization_config=appsync.NamespaceAuthConfig(
# Override publishing authorization to API Key
publish_auth_mode_types=[appsync.AppSyncAuthorizationType.API_KEY],
# Override subscribing authorization to Lambda
subscribe_auth_mode_types=[appsync.AppSyncAuthorizationType.LAMBDA]
)
)
EventApi api;
ChannelNamespace.Builder.create(this, "Namespace")
.api(api)
.authorizationConfig(NamespaceAuthConfig.builder()
// Override publishing authorization to API Key
.publishAuthModeTypes(List.of(AppSyncAuthorizationType.API_KEY))
// Override subscribing authorization to Lambda
.subscribeAuthModeTypes(List.of(AppSyncAuthorizationType.LAMBDA))
.build())
.build();
EventApi api;
new ChannelNamespace(this, "Namespace", new ChannelNamespaceProps {
Api = api,
AuthorizationConfig = new NamespaceAuthConfig {
// Override publishing authorization to API Key
PublishAuthModeTypes = new [] { AppSyncAuthorizationType.API_KEY },
// Override subscribing authorization to Lambda
SubscribeAuthModeTypes = new [] { AppSyncAuthorizationType.LAMBDA }
}
});
var api EventApi
appsync.NewChannelNamespace(this, jsii.String("Namespace"), &ChannelNamespaceProps{
Api: Api,
AuthorizationConfig: &NamespaceAuthConfig{
// Override publishing authorization to API Key
PublishAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_API_KEY,
},
// Override subscribing authorization to Lambda
SubscribeAuthModeTypes: []AppSyncAuthorizationType{
appsync.AppSyncAuthorizationType_LAMBDA,
},
},
})
You can define event handlers on channel namespaces. Event handlers are functions that run on AWS AppSync's JavaScript runtime and enable you to run custom business logic. You can use an event handler to process published events or process and authorize subscribe requests.
For more information, see Channel namespace handlers and event processing.
declare const api: appsync.EventApi;
new appsync.ChannelNamespace(this, 'Namespace', {
api,
// set a handler from inline code
code: appsync.Code.fromInline('/* event handler code here.*/'),
});
new appsync.ChannelNamespace(this, 'Namespace', {
api,
// set a handler from an asset
code: appsync.Code.fromAsset('directory/function_code.js'),
});
# api: appsync.EventApi
appsync.ChannelNamespace(self, "Namespace",
api=api,
# set a handler from inline code
code=appsync.Code.from_inline("/* event handler code here.*/")
)
appsync.ChannelNamespace(self, "Namespace",
api=api,
# set a handler from an asset
code=appsync.Code.from_asset("directory/function_code.js")
)
EventApi api;
ChannelNamespace.Builder.create(this, "Namespace")
.api(api)
// set a handler from inline code
.code(Code.fromInline("/* event handler code here.*/"))
.build();
ChannelNamespace.Builder.create(this, "Namespace")
.api(api)
// set a handler from an asset
.code(Code.fromAsset("directory/function_code.js"))
.build();
EventApi api;
new ChannelNamespace(this, "Namespace", new ChannelNamespaceProps {
Api = api,
// set a handler from inline code
Code = Code.FromInline("/* event handler code here.*/")
});
new ChannelNamespace(this, "Namespace", new ChannelNamespaceProps {
Api = api,
// set a handler from an asset
Code = Code.FromAsset("directory/function_code.js")
});
var api EventApi
appsync.NewChannelNamespace(this, jsii.String("Namespace"), &ChannelNamespaceProps{
Api: Api,
// set a handler from inline code
Code: appsync.Code_FromInline(jsii.String("/* event handler code here.*/")),
})
appsync.NewChannelNamespace(this, jsii.String("Namespace"), &ChannelNamespaceProps{
Api: Api,
// set a handler from an asset
Code: appsync.Code_FromAsset(jsii.String("directory/function_code.js")),
})
You can define an integration in your event handler for onPublish and/or onSubscribe operations. When defining integrations on your channel namespace, you write code in the event handler to submit requests to and process responses from your data source. For example, if you configure an integration with Amazon DynamoDB for onPublish operations, you can persist those events to DynamoDB using a batchPut operation in the request method, and then return the events as normal in the response method. For an integration with Amazon OpenSearch Service, you may use this for onPublish operations to enrich the events.
When using the AWS Lambda data source integration, you can either invoke the Lambda function using the event handler code or you can directly invoke the Lambda function, bypassing the event handler code all together. When using direct invoke, you can choose to invoke the Lambda function synchronously or asynchronously by specifying the invokeType as REQUEST_RESPONSE or EVENT respectively.
Below are examples using Amazon DynamoDB, Amazon EventBridge, and AWS Lambda. You can leverage any supported data source in the same way.
Amazon DynamoDB & Amazon EventBridge
declare const api: appsync.EventApi;
declare const ddbDataSource: appsync.AppSyncDynamoDbDataSource;
declare const ebDataSource: appsync.AppSyncEventBridgeDataSource;
// DynamoDB data source for publish handler
api.addChannelNamespace('ddb-eb-ns', {
code: appsync.Code.fromInline('/* event handler code here.*/'),
publishHandlerConfig: {
dataSource: ddbDataSource,
},
subscribeHandlerConfig: {
dataSource: ebDataSource,
},
});
# api: appsync.EventApi
# ddb_data_source: appsync.AppSyncDynamoDbDataSource
# eb_data_source: appsync.AppSyncEventBridgeDataSource
# DynamoDB data source for publish handler
api.add_channel_namespace("ddb-eb-ns",
code=appsync.Code.from_inline("/* event handler code here.*/"),
publish_handler_config=appsync.HandlerConfig(
data_source=ddb_data_source
),
subscribe_handler_config=appsync.HandlerConfig(
data_source=eb_data_source
)
)
EventApi api;
AppSyncDynamoDbDataSource ddbDataSource;
AppSyncEventBridgeDataSource ebDataSource;
// DynamoDB data source for publish handler
api.addChannelNamespace("ddb-eb-ns", ChannelNamespaceOptions.builder()
.code(Code.fromInline("/* event handler code here.*/"))
.publishHandlerConfig(HandlerConfig.builder()
.dataSource(ddbDataSource)
.build())
.subscribeHandlerConfig(HandlerConfig.builder()
.dataSource(ebDataSource)
.build())
.build());
EventApi api;
AppSyncDynamoDbDataSource ddbDataSource;
AppSyncEventBridgeDataSource ebDataSource;
// DynamoDB data source for publish handler
api.AddChannelNamespace("ddb-eb-ns", new ChannelNamespaceOptions {
Code = Code.FromInline("/* event handler code here.*/"),
PublishHandlerConfig = new HandlerConfig {
DataSource = ddbDataSource
},
SubscribeHandlerConfig = new HandlerConfig {
DataSource = ebDataSource
}
});
var api EventApi
var ddbDataSource AppSyncDynamoDbDataSource
var ebDataSource AppSyncEventBridgeDataSource
// DynamoDB data source for publish handler
api.AddChannelNamespace(jsii.String("ddb-eb-ns"), &ChannelNamespaceOptions{
Code: appsync.Code_FromInline(jsii.String("/* event handler code here.*/")),
PublishHandlerConfig: &HandlerConfig{
DataSource: ddbDataSource,
},
SubscribeHandlerConfig: &HandlerConfig{
DataSource: ebDataSource,
},
})
AWS Lambda
declare const api: appsync.EventApi;
declare const lambdaDataSource: appsync.AppSyncLambdaDataSource;
// Lambda data source for publish handler
api.addChannelNamespace('lambda-ns', {
code: appsync.Code.fromInline('/* event handler code here.*/'),
publishHandlerConfig: {
dataSource: lambdaDataSource,
},
});
// Direct Lambda data source for publish handler
api.addChannelNamespace('lambda-direct-ns', {
publishHandlerConfig: {
dataSource: lambdaDataSource,
direct: true,
},
});
api.addChannelNamespace('lambda-direct-async-ns', {
publishHandlerConfig: {
dataSource: lambdaDataSource,
direct: true,
lambdaInvokeType: appsync.LambdaInvokeType.EVENT,
},
});
# api: appsync.EventApi
# lambda_data_source: appsync.AppSyncLambdaDataSource
# Lambda data source for publish handler
api.add_channel_namespace("lambda-ns",
code=appsync.Code.from_inline("/* event handler code here.*/"),
publish_handler_config=appsync.HandlerConfig(
data_source=lambda_data_source
)
)
# Direct Lambda data source for publish handler
api.add_channel_namespace("lambda-direct-ns",
publish_handler_config=appsync.HandlerConfig(
data_source=lambda_data_source,
direct=True
)
)
api.add_channel_namespace("lambda-direct-async-ns",
publish_handler_config=appsync.HandlerConfig(
data_source=lambda_data_source,
direct=True,
lambda_invoke_type=appsync.LambdaInvokeType.EVENT
)
)
EventApi api;
AppSyncLambdaDataSource lambdaDataSource;
// Lambda data source for publish handler
api.addChannelNamespace("lambda-ns", ChannelNamespaceOptions.builder()
.code(Code.fromInline("/* event handler code here.*/"))
.publishHandlerConfig(HandlerConfig.builder()
.dataSource(lambdaDataSource)
.build())
.build());
// Direct Lambda data source for publish handler
api.addChannelNamespace("lambda-direct-ns", ChannelNamespaceOptions.builder()
.publishHandlerConfig(HandlerConfig.builder()
.dataSource(lambdaDataSource)
.direct(true)
.build())
.build());
api.addChannelNamespace("lambda-direct-async-ns", ChannelNamespaceOptions.builder()
.publishHandlerConfig(HandlerConfig.builder()
.dataSource(lambdaDataSource)
.direct(true)
.lambdaInvokeType(LambdaInvokeType.EVENT)
.build())
.build());
EventApi api;
AppSyncLambdaDataSource lambdaDataSource;
// Lambda data source for publish handler
api.AddChannelNamespace("lambda-ns", new ChannelNamespaceOptions {
Code = Code.FromInline("/* event handler code here.*/"),
PublishHandlerConfig = new HandlerConfig {
DataSource = lambdaDataSource
}
});
// Direct Lambda data source for publish handler
api.AddChannelNamespace("lambda-direct-ns", new ChannelNamespaceOptions {
PublishHandlerConfig = new HandlerConfig {
DataSource = lambdaDataSource,
Direct = true
}
});
api.AddChannelNamespace("lambda-direct-async-ns", new ChannelNamespaceOptions {
PublishHandlerConfig = new HandlerConfig {
DataSource = lambdaDataSource,
Direct = true,
LambdaInvokeType = LambdaInvokeType.EVENT
}
});
var api EventApi
var lambdaDataSource AppSyncLambdaDataSource
// Lambda data source for publish handler
api.AddChannelNamespace(jsii.String("lambda-ns"), &ChannelNamespaceOptions{
Code: appsync.Code_FromInline(jsii.String("/* event handler code here.*/")),
PublishHandlerConfig: &HandlerConfig{
DataSource: lambdaDataSource,
},
})
// Direct Lambda data source for publish handler
api.AddChannelNamespace(jsii.String("lambda-direct-ns"), &ChannelNamespaceOptions{
PublishHandlerConfig: &HandlerConfig{
DataSource: lambdaDataSource,
Direct: jsii.Boolean(true),
},
})
api.AddChannelNamespace(jsii.String("lambda-direct-async-ns"), &ChannelNamespaceOptions{
PublishHandlerConfig: &HandlerConfig{
DataSource: lambdaDataSource,
Direct: jsii.Boolean(true),
LambdaInvokeType: appsync.LambdaInvokeType_EVENT,
},
})
Types
| Name | Kind | Summary |
|---|---|---|
ApiBase | Construct (L2) | Base Class for API. |
AppsyncFunction | Construct (L2) | AppSync Functions are local functions that perform certain operations onto a backend data source. |
ChannelNamespace | Construct (L2) | A Channel Namespace. |
EventApi | Construct (L2) | An AppSync Event API. |
EventApiBase | Construct (L2) | Base Class for Event API. |
GraphqlApi | Construct (L2) | An AppSync GraphQL API. |
GraphqlApiBase | Construct (L2) | Base Class for GraphQL API. |
SourceApiAssociation | Construct (L2) | AppSync SourceApiAssociation which associates an AppSync source API to an AppSync Merged API. |
CfnApi | Construct (L1) | The AWS::AppSync::Api resource creates an AWS AppSync API that you can use for an AWS AppSync API with your preferred configuration, such as an Event API that provides real-time message publishing and message subscriptions over WebSockets. |
CfnApiCache | Construct (L1) | The AWS::AppSync::ApiCache resource represents the input of a CreateApiCache operation. |
CfnApiKey | Construct (L1) | The AWS::AppSync::ApiKey resource creates a unique key that you can distribute to clients who are executing GraphQL operations with AWS AppSync that require an API key. |
CfnChannelNamespace | Construct (L1) | The AWS::AppSync::ChannelNamespace resource creates a channel namespace associated with an Api . |
CfnDataSource | Construct (L1) | The AWS::AppSync::DataSource resource creates data sources for resolvers in AWS AppSync to connect to, such as Amazon DynamoDB , AWS Lambda , and Amazon OpenSearch Service . |
CfnDomainName | Construct (L1) | The AWS::AppSync::DomainName resource creates a DomainNameConfig object to configure a custom domain. |
CfnDomainNameApiAssociation | Construct (L1) | The AWS::AppSync::DomainNameApiAssociation resource represents the mapping of your custom domain name to the assigned API URL. |
CfnFunctionConfiguration | Construct (L1) | The AWS::AppSync::FunctionConfiguration resource defines the functions in GraphQL APIs to perform certain operations. |
CfnGraphQLApi | Construct (L1) | The AWS::AppSync::GraphQLApi resource creates a new AWS AppSync GraphQL API. |
CfnGraphQLSchema | Construct (L1) | The AWS::AppSync::GraphQLSchema resource is used for your AWS AppSync GraphQL schema that controls the data model for your API. |
CfnResolver | Construct (L1) | The AWS::AppSync::Resolver resource defines the logical GraphQL resolver that you attach to fields in a schema. |
CfnSourceApiAssociation | Construct (L1) | Describes the configuration of a source API. |
CfnType | Construct (L1) | Represents a GraphQL type in an AWS AppSync GraphQL API. |
ApiKeyConfig | Struct | Configuration for API Key authorization in AppSync. |
AppSyncApiKeyConfig | Struct | Configuration for API Key authorization in AppSync. |
AppSyncAuthorizationType | Enum | enum with all possible values for AppSync authorization type. |
AppSyncAuthProvider | Struct | Auth provider settings for AppSync Event APIs. |
AppSyncAwsIamConfig | Struct | The authorization config in case the HTTP endpoint requires authorization. |
AppSyncBackedDataSource | Construct | Abstract AppSync datasource implementation. |
AppSyncBackedDataSourceProps | Struct | Properties for an AppSync datasource backed by a resource. |
AppSyncBaseDataSource | Construct | Abstract AppSync datasource implementation. |
AppSyncBaseDataSourceProps | Struct | Base properties for an AppSync datasource. |
AppSyncCognitoConfig | Struct | Configuration for Cognito user-pools in AppSync for Api. |
AppSyncDataSourceOptions | Struct | Optional configuration for data sources. |
AppSyncDataSourceType | Enum | Valid data source types for AppSync. |
AppSyncDomainOptions | Struct | Domain name configuration for AppSync. |
AppSyncDynamoDbDataSource | Construct | An AppSync datasource backed by a DynamoDB table. |
AppSyncDynamoDbDataSourceProps | Struct | Properties for an AppSync DynamoDB datasource. |
AppSyncEventBridgeDataSource | Construct | An AppSync datasource backed by EventBridge. |
AppSyncEventBridgeDataSourceProps | Struct | Properties for an AppSync EventBridge datasource. |
AppSyncEventResource | Class | A class used to generate resource arns for AppSync Event APIs. |
AppSyncExtendedDataSourceProps | Struct | Props used by implementations of BaseDataSource to provide configuration. |
AppSyncFieldLogLevel | Enum | log-level for fields in AppSync. |
AppsyncFunctionAttributes | Struct | The attributes for imported AppSync Functions. |
AppsyncFunctionProps | Struct | the CDK properties for AppSync Functions. |
AppSyncHttpDataSource | Construct | An AppSync datasource backed by a http endpoint. |
AppSyncHttpDataSourceOptions | Struct | Optional configuration for Http data sources. |
AppSyncHttpDataSourceProps | Struct | Properties for an AppSync http datasource. |
AppSyncLambdaAuthorizerConfig | Struct | Configuration for Lambda authorization in AppSync. |
AppSyncLambdaDataSource | Construct | An AppSync datasource backed by a Lambda function. |
AppSyncLambdaDataSourceProps | Struct | Properties for an AppSync Lambda datasource. |
AppSyncLogConfig | Struct | Logging configuration for AppSync. |
AppSyncOpenIdConnectConfig | Struct | Configuration for OpenID Connect authorization in AppSync. |
AppSyncOpenSearchDataSource | Construct | An Appsync datasource backed by OpenSearch. |
AppSyncOpenSearchDataSourceProps | Struct | Properties for the OpenSearch Data Source. |
AppSyncRdsDataSource | Construct | An AppSync datasource backed by RDS. |
AppSyncRdsDataSourceProps | Struct | Properties for an AppSync RDS datasource Aurora Serverless V1. |
AppSyncRdsDataSourcePropsV2 | Struct | Properties for an AppSync RDS datasource Aurora Serverless V2. |
AssetCode | Class | Represents a local file with source code used for an AppSync Function or Resolver. |
Assign | Class | Utility class representing the assigment of a value to an attribute. |
AttributeValues | Class | Specifies the attribute value assignments. |
AttributeValuesStep | Class | Utility class to allow assigning a value to an attribute. |
AuthorizationConfig | Struct | Configuration of the API authorization modes. |
AuthorizationMode | Struct | Interface to specify default or additional authorization(s). |
AuthorizationType | Enum | enum with all possible values for AppSync authorization type. |
AwsIamConfig | Struct | The authorization config in case the HTTP endpoint requires authorization. |
BackedDataSource | Construct | Abstract AppSync datasource implementation. |
BackedDataSourceProps | Struct | properties for an AppSync datasource backed by a resource. |
BaseAppsyncFunctionProps | Struct | the base properties for AppSync Functions. |
BaseChannelNamespaceProps | Struct | the base properties for a channel namespace. |
BaseDataSource | Construct | Abstract AppSync datasource implementation. |
BaseDataSourceProps | Struct | Base properties for an AppSync datasource. |
BaseResolverProps | Struct | Basic properties for an AppSync resolver. |
CachingConfig | Struct | CachingConfig for AppSync resolvers. |
CfnApi.AuthModeProperty | Struct | Describes an authorization configuration. |
CfnApi.AuthProviderProperty | Struct | Describes an authorization provider. |
CfnApi.CognitoConfigProperty | Struct | Describes an Amazon Cognito configuration. |
CfnApi.DnsMapProperty | Struct | A map of DNS names for the Api. |
CfnApi.EventConfigProperty | Struct | Describes the authorization configuration for connections, message publishing, message subscriptions, and logging for an Event API. |
CfnApi.EventLogConfigProperty | Struct | Describes the CloudWatch Logs configuration for the Event API. |
CfnApi.LambdaAuthorizerConfigProperty | Struct | A LambdaAuthorizerConfig specifies how to authorize AWS AppSync API access when using the AWS_LAMBDA authorizer mode. |
CfnApi.OpenIDConnectConfigProperty | Struct | Describes an OpenID Connect (OIDC) configuration. |
CfnApiCacheProps | Struct | Properties for defining a CfnApiCache. |
CfnApiKeyProps | Struct | Properties for defining a CfnApiKey. |
CfnApiProps | Struct | Properties for defining a CfnApi. |
CfnChannelNamespace.AuthModeProperty | Struct | Describes an authorization configuration. |
CfnChannelNamespace.HandlerConfigProperty | Struct | The HandlerConfig property type specifies the configuration for the handler. |
CfnChannelNamespace.HandlerConfigsProperty | Struct | The HandlerConfigs property type specifies the configuration for the OnPublish and OnSubscribe handlers. |
CfnChannelNamespace.IntegrationProperty | Struct | The Integration property type specifies the integration data source configuration for the handler. |
CfnChannelNamespace.LambdaConfigProperty | Struct | The LambdaConfig property type specifies the integration configuration for a Lambda data source. |
CfnChannelNamespaceProps | Struct | Properties for defining a CfnChannelNamespace. |
CfnDataSource.AuthorizationConfigProperty | Struct | The AuthorizationConfig property type specifies the authorization type and configuration for an AWS AppSync http data source. |
CfnDataSource.AwsIamConfigProperty | Struct | Use the AwsIamConfig property type to specify AwsIamConfig for a AWS AppSync authorizaton. |
CfnDataSource.DeltaSyncConfigProperty | Struct | Describes a Delta Sync configuration. |
CfnDataSource.DynamoDBConfigProperty | Struct | The DynamoDBConfig property type specifies the AwsRegion and TableName for an Amazon DynamoDB table in your account for an AWS AppSync data source. |
CfnDataSource.ElasticsearchConfigProperty | Struct | |
CfnDataSource.EventBridgeConfigProperty | Struct | The data source. |
CfnDataSource.HttpConfigProperty | Struct | Use the HttpConfig property type to specify HttpConfig for an AWS AppSync data source. |
CfnDataSource.LambdaConfigProperty | Struct | The LambdaConfig property type specifies the Lambda function ARN for an AWS AppSync data source. |
CfnDataSource.OpenSearchServiceConfigProperty | Struct | The OpenSearchServiceConfig property type specifies the AwsRegion and Endpoints for an Amazon OpenSearch Service domain in your account for an AWS AppSync data source. |
CfnDataSource.RdsHttpEndpointConfigProperty | Struct | Use the RdsHttpEndpointConfig property type to specify the RdsHttpEndpoint for an AWS AppSync relational database. |
CfnDataSource.RelationalDatabaseConfigProperty | Struct | Use the RelationalDatabaseConfig property type to specify RelationalDatabaseConfig for an AWS AppSync data source. |
CfnDataSourceProps | Struct | Properties for defining a CfnDataSource. |
CfnDomainNameApiAssociationProps | Struct | Properties for defining a CfnDomainNameApiAssociation. |
CfnDomainNameProps | Struct | Properties for defining a CfnDomainName. |
CfnFunctionConfiguration.AppSyncRuntimeProperty | Struct | Describes a runtime used by an AWS AppSync resolver or AWS AppSync function. |
CfnFunctionConfiguration.LambdaConflictHandlerConfigProperty | Struct | The LambdaConflictHandlerConfig object when configuring LAMBDA as the Conflict Handler. |
CfnFunctionConfiguration.SyncConfigProperty | Struct | Describes a Sync configuration for a resolver. |
CfnFunctionConfigurationProps | Struct | Properties for defining a CfnFunctionConfiguration. |
CfnGraphQLApi.AdditionalAuthenticationProviderProperty | Struct | Describes an additional authentication provider. |
CfnGraphQLApi.CognitoUserPoolConfigProperty | Struct | Describes an Amazon Cognito user pool configuration. |
CfnGraphQLApi.EnhancedMetricsConfigProperty | Struct | Describes an enhanced metrics configuration. |
CfnGraphQLApi.LambdaAuthorizerConfigProperty | Struct | Configuration for AWS Lambda function authorization. |
CfnGraphQLApi.LogConfigProperty | Struct | The LogConfig property type specifies the logging configuration when writing GraphQL operations and tracing to Amazon CloudWatch for an AWS AppSync GraphQL API. |
CfnGraphQLApi.OpenIDConnectConfigProperty | Struct | The OpenIDConnectConfig property type specifies the optional authorization configuration for using an OpenID Connect compliant service with your GraphQL endpoint for an AWS AppSync GraphQL API. |
CfnGraphQLApi.UserPoolConfigProperty | Struct | The UserPoolConfig property type specifies the optional authorization configuration for using Amazon Cognito user pools with your GraphQL endpoint for an AWS AppSync GraphQL API. |
CfnGraphQLApiProps | Struct | Properties for defining a CfnGraphQLApi. |
CfnGraphQLSchemaProps | Struct | Properties for defining a CfnGraphQLSchema. |
CfnResolver.AppSyncRuntimeProperty | Struct | Describes a runtime used by an AWS AppSync resolver or AWS AppSync function. |
CfnResolver.CachingConfigProperty | Struct | The caching configuration for a resolver that has caching activated. |
CfnResolver.LambdaConflictHandlerConfigProperty | Struct | The LambdaConflictHandlerConfig when configuring LAMBDA as the Conflict Handler. |
CfnResolver.PipelineConfigProperty | Struct | Use the PipelineConfig property type to specify PipelineConfig for an AWS AppSync resolver. |
CfnResolver.SyncConfigProperty | Struct | Describes a Sync configuration for a resolver. |
CfnResolverProps | Struct | Properties for defining a CfnResolver. |
CfnSourceApiAssociation.SourceApiAssociationConfigProperty | Struct | Describes properties used to specify configurations related to a source API. |
CfnSourceApiAssociationProps | Struct | Properties for defining a CfnSourceApiAssociation. |
CfnTypeProps | Struct | Properties for defining a CfnType. |
ChannelNamespaceOptions | Struct | Option configuration for channel namespace. |
ChannelNamespaceProps | Struct | Additional property for an AppSync channel namespace for an Event API reference. |
Code | Class | Represents source code for an AppSync Function or Resolver. |
CodeConfig | Struct | Result of binding Code into a Function. |
DataSourceLevelMetricsBehavior | Enum | Controls how data source metrics will be emitted to CloudWatch. |
DataSourceMetricsConfig | Enum | Enum for enhanced data source metrics for specified data sources. |
DataSourceOptions | Struct | Optional configuration for data sources. |
Definition | Class | AppSync definition. |
DomainOptions | Struct | Domain name configuration for AppSync. |
DynamoDbDataSource | Construct | An AppSync datasource backed by a DynamoDB table. |
DynamoDbDataSourceProps | Struct | Properties for an AppSync DynamoDB datasource. |
ElasticsearchDataSource | Construct | An Appsync datasource backed by Elasticsearch. |
ElasticsearchDataSourceProps | Struct | Properties for the Elasticsearch Data Source. |
EnhancedMetricsConfig | Struct | Enhanced metrics configuration for AppSync. |
EventApiAttributes | Struct | Attributes for Event API imports. |
EventApiAuthConfig | Struct | Authorization configuration for the Event API. |
EventApiProps | Struct | Properties for an AppSync Event API. |
EventBridgeDataSource | Construct | An AppSync datasource backed by EventBridge. |
EventBridgeDataSourceProps | Struct | Properties for an AppSync EventBridge datasource. |
ExtendedDataSourceProps | Struct | props used by implementations of BaseDataSource to provide configuration. |
ExtendedResolverProps | Struct | Additional property for an AppSync resolver for data source reference. |
FieldLogLevel | Enum | log-level for fields in AppSync. |
FunctionRuntime | Class | Utility class for specifying specific appsync runtime versions. |
FunctionRuntimeFamily | Enum | Appsync supported runtimes. |
GraphqlApiAttributes | Struct | Attributes for GraphQL imports. |
GraphqlApiProps | Struct | Properties for an AppSync GraphQL API. |
HandlerBehavior | Enum | Enumerated type for the handler behavior for a channel namespace. |
HandlerConfig | Struct | Handler configuration construct for onPublish and onSubscribe. |
HttpDataSource | Construct | An AppSync datasource backed by a http endpoint. |
HttpDataSourceOptions | Struct | Optional configuration for Http data sources. |
HttpDataSourceProps | Struct | Properties for an AppSync http datasource. |
IamResource | Class | A class used to generate resource arns for AppSync. |
IApi | Interface | Interface for an API. |
IAppSyncAuthConfig | Interface | Exposes methods for defining authorization config for AppSync APIs. |
IAppsyncFunction | Interface | Interface for AppSync Functions. |
IChannelNamespace | Interface | An AppSync channel namespace. |
IEventApi | Interface | Interface for Event API. |
IGraphqlApi | Interface | Interface for GraphQL. |
InlineCode | Class | AppSync function code from an inline string. |
IntrospectionConfig | Enum | Introspection configuration for a GraphQL API. |
ISchema | Interface | Interface for implementing your own schema. |
ISchemaConfig | Interface | Configuration for bound graphql schema. |
ISourceApiAssociation | Interface | Interface for AppSync Source Api Association. |
KeyCondition | Class | Factory class for DynamoDB key conditions. |
LambdaAuthorizerConfig | Struct | Configuration for Lambda authorization in AppSync. |
LambdaDataSource | Construct | An AppSync datasource backed by a Lambda function. |
LambdaDataSourceProps | Struct | Properties for an AppSync Lambda datasource. |
LambdaInvokeType | Enum | Invoke types for direct Lambda data sources. |
LogConfig | Struct | Logging configuration for AppSync. |
MappingTemplate | Class | MappingTemplates for AppSync resolvers. |
MergeType | Enum | Merge type used to associate the source API. |
NamespaceAuthConfig | Struct | Authorization configuration for the Channel Namespace. |
NoneDataSource | Construct | An AppSync dummy datasource. |
NoneDataSourceProps | Struct | Properties for an AppSync dummy datasource. |
OpenIdConnectConfig | Struct | Configuration for OpenID Connect authorization in AppSync. |
OpenSearchDataSource | Construct | An Appsync datasource backed by OpenSearch. |
OpenSearchDataSourceProps | Struct | Properties for the OpenSearch Data Source. |
OperationLevelMetricsConfig | Enum | Controls how operation metrics will be emitted to CloudWatch. |
PartitionKey | Class | Specifies the assignment to the partition key. |
PartitionKeyStep | Class | Utility class to allow assigning a value or an auto-generated id to a partition key. |
PrimaryKey | Class | Specifies the assignment to the primary key. |
RdsDataSource | Construct | An AppSync datasource backed by RDS. |
RdsDataSourceProps | Struct | Properties for an AppSync RDS datasource Aurora Serverless V1. |
RdsDataSourcePropsV2 | Struct | Properties for an AppSync RDS datasource Aurora Serverless V2. |
Resolver | Construct | An AppSync resolver. |
ResolverLevelMetricsBehavior | Enum | Controls how resolver metrics will be emitted to CloudWatch. |
ResolverMetricsConfig | Enum | Enum for enhanced resolver metrics for specified resolvers. |
ResolverProps | Struct | Additional property for an AppSync resolver for GraphQL API reference. |
RuntimeConfig | Struct | Config for binding runtime to a function or resolver. |
SchemaBindOptions | Struct | Used for configuring schema bind behavior. |
SchemaFile | Class | The Schema for a GraphQL Api. |
SchemaProps | Struct | The options for configuring a schema from an existing file. |
SortKeyStep | Class | Utility class to allow assigning a value or an auto-generated id to a sort key. |
SourceApi | Struct | Configuration of source API. |
SourceApiAssociationAttributes | Struct | The attributes for imported AppSync Source Api Association. |
SourceApiAssociationProps | Struct | Properties for SourceApiAssociation which associates an AppSync Source API with an AppSync Merged API. |
SourceApiOptions | Struct | Additional API configuration for creating a AppSync Merged API. |
UserPoolConfig | Struct | Configuration for Cognito user-pools in AppSync. |
UserPoolDefaultAction | Enum | enum with all possible values for Cognito user-pool default actions. |
Values | Class | Factory class for attribute value assignments. |
Visibility | Enum | Visibility type for a GraphQL API. |