Skip to content
v2.274.0

AWS AppSync Construct Library ​

The aws-cdk-lib/aws-appsync package contains constructs for building flexible APIs that use GraphQL and Events.

ts
import * as appsync from 'aws-cdk-lib/aws-appsync';
python
import aws_cdk.aws_appsync as appsync
java
import software.amazon.awscdk.services.appsync.*;
csharp
using Amazon.CDK.AWS.AppSync;
go
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:

gql
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:

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(),
});
python
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()
)
java
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());
csharp
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()
});
go
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 ​
ts
// 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])
  `),
});
python
# 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])
          """)
)
java
// 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());
csharp
// 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])
      ")
});
go
// 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 ​
ts
// 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])
  `),
});
python
# 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])
          """)
)
java
// 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());
csharp
// 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])
      ")
});
go
// 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:

gql
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:

json
{
  "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:

json
{
  "id": "${context.result.id}"
}

CDK stack file app-stack.ts:

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'),
});
python
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")
)
java
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());
csharp
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")
});
go
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:

gql
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:

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'),
});
python
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")
)
java
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());
csharp
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")
});
go
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.

ts
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
  ]`),
});
python
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
          ]""")
)
java
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());
csharp
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
      ]")
});
go
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.

ts
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,
      }
    ],
  }),
});
python
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
        )
        ]
    )
)
java
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();
csharp
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
        } }
    })
});
go
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.

ts
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,
});
python
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
)
java
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();
csharp
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
});
go
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.

ts
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,
});
python
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
)
java
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();
csharp
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
});
go
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.

ts
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,
  },
});
python
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
    )
)
java
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();
csharp
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
    }
});
go
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

ts
const api = new appsync.GraphqlApi(this, 'api', {
  name: 'myApi',
  definition: appsync.Definition.fromFile(path.join(__dirname, 'schema.graphl')),
});
python
api = appsync.GraphqlApi(self, "api",
    name="myApi",
    definition=appsync.Definition.from_file(path.join(__dirname, "schema.graphl"))
)
java
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
        .name("myApi")
        .definition(Definition.fromFile(join(__dirname, "schema.graphl")))
        .build();
csharp
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "myApi",
    Definition = Definition.FromFile(Join(__dirname, "schema.graphl"))
});
go
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.

ts
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);
python
# 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)
java
GraphqlApi api;
Table table;

IGraphqlApi importedApi = GraphqlApi.fromGraphqlApiAttributes(this, "IApi", GraphqlApiAttributes.builder()
        .graphqlApiId(api.getApiId())
        .graphqlApiArn(api.getArn())
        .build());
importedApi.addDynamoDbDataSource("TableDataSource", table);
csharp
GraphqlApi api;
Table table;

var importedApi = GraphqlApi.FromGraphqlApiAttributes(this, "IApi", new GraphqlApiAttributes {
    GraphqlApiId = api.ApiId,
    GraphqlApiArn = api.Arn
});
importedApi.AddDynamoDbDataSource("TableDataSource", table);
go
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:

ts
const api = new appsync.GraphqlApi(this, 'api', {
  name: 'MyPrivateAPI',
  definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.schema.graphql')),
  visibility: appsync.Visibility.PRIVATE,
});
python
api = appsync.GraphqlApi(self, "api",
    name="MyPrivateAPI",
    definition=appsync.Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
    visibility=appsync.Visibility.PRIVATE
)
java
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
        .name("MyPrivateAPI")
        .definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
        .visibility(Visibility.PRIVATE)
        .build();
csharp
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "MyPrivateAPI",
    Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
    Visibility = Visibility.PRIVATE
});
go
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.

ts
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`.
      },
    },
  },
});
python
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
            )
        )
    )
)
java
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();
csharp
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
            }
        }
    }
});
go
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:

gql
type Mutation {
  updateExample(...): ...
    @aws_iam
}

In IAM:

json
{
  "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.

ts
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');
python
# 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")
java
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");
csharp
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");
go
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)
ts
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');
python
# 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")
java
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");
csharp
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");
go
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.

ts
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'),
});
python
# 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")
)
java
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();
csharp
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")
});
go
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.

ts
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,
});
python
# 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
)
java
GraphqlApi api;
LambdaDataSource lambdaDataSource;


AppsyncFunction appsyncFunction = AppsyncFunction.Builder.create(this, "function")
        .name("appsync_function")
        .api(api)
        .dataSource(lambdaDataSource)
        .maxBatchSize(10)
        .build();
csharp
GraphqlApi api;
LambdaDataSource lambdaDataSource;


var appsyncFunction = new AppsyncFunction(this, "function", new AppsyncFunctionProps {
    Name = "appsync_function",
    Api = api,
    DataSource = lambdaDataSource,
    MaxBatchSize = 10
});
go
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.

ts
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'),
});
python
# 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")
)
java
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();
csharp
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")
});
go
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.

ts
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],
});
python
# 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]
)
java
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();
csharp
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 }
});
go
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.

ts
const api = new appsync.GraphqlApi(this, 'api', {
  name: 'DisableIntrospectionApi',
  definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.schema.graphql')),
  introspectionConfig: appsync.IntrospectionConfig.DISABLED,
});
python
api = appsync.GraphqlApi(self, "api",
    name="DisableIntrospectionApi",
    definition=appsync.Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
    introspection_config=appsync.IntrospectionConfig.DISABLED
)
java
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
        .name("DisableIntrospectionApi")
        .definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
        .introspectionConfig(IntrospectionConfig.DISABLED)
        .build();
csharp
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "DisableIntrospectionApi",
    Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
    IntrospectionConfig = IntrospectionConfig.DISABLED
});
go
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.

ts
const api = new appsync.GraphqlApi(this, 'api', {
  name: 'LimitQueryDepths',
  definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.schema.graphql')),
  queryDepthLimit: 2,
});
python
api = appsync.GraphqlApi(self, "api",
    name="LimitQueryDepths",
    definition=appsync.Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
    query_depth_limit=2
)
java
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
        .name("LimitQueryDepths")
        .definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
        .queryDepthLimit(2)
        .build();
csharp
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "LimitQueryDepths",
    Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
    QueryDepthLimit = 2
});
go
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.

ts
const api = new appsync.GraphqlApi(this, 'api', {
  name: 'LimitResolverCount',
  definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.schema.graphql')),
  resolverCountLimit: 2,
});
python
api = appsync.GraphqlApi(self, "api",
    name="LimitResolverCount",
    definition=appsync.Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
    resolver_count_limit=2
)
java
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
        .name("LimitResolverCount")
        .definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
        .resolverCountLimit(2)
        .build();
csharp
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "LimitResolverCount",
    Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
    ResolverCountLimit = 2
});
go
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.

ts
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');
python
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")
java
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");
csharp
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");
go
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.

ts
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',
  }),
}));
python
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"
    })
))
java
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());
csharp
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" }
    })
}));
go
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.

ts
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',
});
python
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"
)
java
GraphqlApi api = GraphqlApi.Builder.create(this, "OwnerContact")
        .name("OwnerContact")
        .definition(Definition.fromSchema(SchemaFile.fromAsset(join(__dirname, "appsync.test.graphql"))))
        .ownerContact("test-owner-contact")
        .build();
csharp
var api = new GraphqlApi(this, "OwnerContact", new GraphqlApiProps {
    Name = "OwnerContact",
    Definition = Definition.FromSchema(SchemaFile.FromAsset(Join(__dirname, "appsync.test.graphql"))),
    OwnerContact = "test-owner-contact"
});
go
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.

ts
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,
  },
});
python
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
    )
)
java
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();
csharp
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
    }
});
go
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.

ts
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,
});
python
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
)
java
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());
csharp
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
});
go
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.

ts
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');
python
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")
java
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");
csharp
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");
go
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.

ts
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');
python
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")
java
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");
csharp
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");
go
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.

ts
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');
python
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")
java
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");
csharp
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");
go
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 ​

ts
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);
python
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)
java
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);
csharp
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);
go
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 ​

ts
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);
python
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)
java
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);
csharp
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);
go
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 ​

ts
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);
python
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)
java
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);
csharp
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);
go
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 ​

ts
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);
python
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)
java
import software.amazon.awscdk.services.lambda.*;

Function lambdaDs;


EventApi api = EventApi.Builder.create(this, "EventApiLambda")
        .apiName("LambdaEventApi")
        .build();

AppSyncLambdaDataSource dataSource = api.addLambdaDataSource("lambdads", lambdaDs);
csharp
using Amazon.CDK.AWS.Lambda;

Function lambdaDs;


var api = new EventApi(this, "EventApiLambda", new EventApiProps {
    ApiName = "LambdaEventApi"
});

var dataSource = api.AddLambdaDataSource("lambdads", lambdaDs);
go
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 ​

ts
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);
python
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)
java
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);
csharp
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);
go
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 ​

ts
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`);
python
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")
java
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));
csharp
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");
go
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.

ts
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 });
python
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)
java
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();
csharp
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 });
go
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.

ts
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');
python
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")
java
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");
csharp
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");
go
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.

ts
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,
});
python
# 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
)
java
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();
csharp
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
});
go
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.

ts
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', {});
python
# 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")
java
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());
csharp
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 { });
go
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.

ts
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],
  },
});
python
# 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]
    )
)
java
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();
csharp
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 }
    }
});
go
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.

ts
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'),
});
python
# 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")
)
java
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();
csharp
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")
});
go
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 ​

ts
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,
  },
});
python
# 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
    )
)
java
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());
csharp
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
    }
});
go
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 ​

ts
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,
  },
});
python
# 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
    )
)
java
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());
csharp
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
    }
});
go
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 ​

NameKindSummary
ApiBaseConstruct (L2)Base Class for API.
AppsyncFunctionConstruct (L2)AppSync Functions are local functions that perform certain operations onto a backend data source.
ChannelNamespaceConstruct (L2)A Channel Namespace.
EventApiConstruct (L2)An AppSync Event API.
EventApiBaseConstruct (L2)Base Class for Event API.
GraphqlApiConstruct (L2)An AppSync GraphQL API.
GraphqlApiBaseConstruct (L2)Base Class for GraphQL API.
SourceApiAssociationConstruct (L2)AppSync SourceApiAssociation which associates an AppSync source API to an AppSync Merged API.
CfnApiConstruct (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.
CfnApiCacheConstruct (L1)The AWS::AppSync::ApiCache resource represents the input of a CreateApiCache operation.
CfnApiKeyConstruct (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.
CfnChannelNamespaceConstruct (L1)The AWS::AppSync::ChannelNamespace resource creates a channel namespace associated with an Api .
CfnDataSourceConstruct (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 .
CfnDomainNameConstruct (L1)The AWS::AppSync::DomainName resource creates a DomainNameConfig object to configure a custom domain.
CfnDomainNameApiAssociationConstruct (L1)The AWS::AppSync::DomainNameApiAssociation resource represents the mapping of your custom domain name to the assigned API URL.
CfnFunctionConfigurationConstruct (L1)The AWS::AppSync::FunctionConfiguration resource defines the functions in GraphQL APIs to perform certain operations.
CfnGraphQLApiConstruct (L1)The AWS::AppSync::GraphQLApi resource creates a new AWS AppSync GraphQL API.
CfnGraphQLSchemaConstruct (L1)The AWS::AppSync::GraphQLSchema resource is used for your AWS AppSync GraphQL schema that controls the data model for your API.
CfnResolverConstruct (L1)The AWS::AppSync::Resolver resource defines the logical GraphQL resolver that you attach to fields in a schema.
CfnSourceApiAssociationConstruct (L1)Describes the configuration of a source API.
CfnTypeConstruct (L1)Represents a GraphQL type in an AWS AppSync GraphQL API.
ApiKeyConfigStructConfiguration for API Key authorization in AppSync.
AppSyncApiKeyConfigStructConfiguration for API Key authorization in AppSync.
AppSyncAuthorizationTypeEnumenum with all possible values for AppSync authorization type.
AppSyncAuthProviderStructAuth provider settings for AppSync Event APIs.
AppSyncAwsIamConfigStructThe authorization config in case the HTTP endpoint requires authorization.
AppSyncBackedDataSourceConstructAbstract AppSync datasource implementation.
AppSyncBackedDataSourcePropsStructProperties for an AppSync datasource backed by a resource.
AppSyncBaseDataSourceConstructAbstract AppSync datasource implementation.
AppSyncBaseDataSourcePropsStructBase properties for an AppSync datasource.
AppSyncCognitoConfigStructConfiguration for Cognito user-pools in AppSync for Api.
AppSyncDataSourceOptionsStructOptional configuration for data sources.
AppSyncDataSourceTypeEnumValid data source types for AppSync.
AppSyncDomainOptionsStructDomain name configuration for AppSync.
AppSyncDynamoDbDataSourceConstructAn AppSync datasource backed by a DynamoDB table.
AppSyncDynamoDbDataSourcePropsStructProperties for an AppSync DynamoDB datasource.
AppSyncEventBridgeDataSourceConstructAn AppSync datasource backed by EventBridge.
AppSyncEventBridgeDataSourcePropsStructProperties for an AppSync EventBridge datasource.
AppSyncEventResourceClassA class used to generate resource arns for AppSync Event APIs.
AppSyncExtendedDataSourcePropsStructProps used by implementations of BaseDataSource to provide configuration.
AppSyncFieldLogLevelEnumlog-level for fields in AppSync.
AppsyncFunctionAttributesStructThe attributes for imported AppSync Functions.
AppsyncFunctionPropsStructthe CDK properties for AppSync Functions.
AppSyncHttpDataSourceConstructAn AppSync datasource backed by a http endpoint.
AppSyncHttpDataSourceOptionsStructOptional configuration for Http data sources.
AppSyncHttpDataSourcePropsStructProperties for an AppSync http datasource.
AppSyncLambdaAuthorizerConfigStructConfiguration for Lambda authorization in AppSync.
AppSyncLambdaDataSourceConstructAn AppSync datasource backed by a Lambda function.
AppSyncLambdaDataSourcePropsStructProperties for an AppSync Lambda datasource.
AppSyncLogConfigStructLogging configuration for AppSync.
AppSyncOpenIdConnectConfigStructConfiguration for OpenID Connect authorization in AppSync.
AppSyncOpenSearchDataSourceConstructAn Appsync datasource backed by OpenSearch.
AppSyncOpenSearchDataSourcePropsStructProperties for the OpenSearch Data Source.
AppSyncRdsDataSourceConstructAn AppSync datasource backed by RDS.
AppSyncRdsDataSourcePropsStructProperties for an AppSync RDS datasource Aurora Serverless V1.
AppSyncRdsDataSourcePropsV2StructProperties for an AppSync RDS datasource Aurora Serverless V2.
AssetCodeClassRepresents a local file with source code used for an AppSync Function or Resolver.
AssignClassUtility class representing the assigment of a value to an attribute.
AttributeValuesClassSpecifies the attribute value assignments.
AttributeValuesStepClassUtility class to allow assigning a value to an attribute.
AuthorizationConfigStructConfiguration of the API authorization modes.
AuthorizationModeStructInterface to specify default or additional authorization(s).
AuthorizationTypeEnumenum with all possible values for AppSync authorization type.
AwsIamConfigStructThe authorization config in case the HTTP endpoint requires authorization.
BackedDataSourceConstructAbstract AppSync datasource implementation.
BackedDataSourcePropsStructproperties for an AppSync datasource backed by a resource.
BaseAppsyncFunctionPropsStructthe base properties for AppSync Functions.
BaseChannelNamespacePropsStructthe base properties for a channel namespace.
BaseDataSourceConstructAbstract AppSync datasource implementation.
BaseDataSourcePropsStructBase properties for an AppSync datasource.
BaseResolverPropsStructBasic properties for an AppSync resolver.
CachingConfigStructCachingConfig for AppSync resolvers.
CfnApi.AuthModePropertyStructDescribes an authorization configuration.
CfnApi.AuthProviderPropertyStructDescribes an authorization provider.
CfnApi.CognitoConfigPropertyStructDescribes an Amazon Cognito configuration.
CfnApi.DnsMapPropertyStructA map of DNS names for the Api.
CfnApi.EventConfigPropertyStructDescribes the authorization configuration for connections, message publishing, message subscriptions, and logging for an Event API.
CfnApi.EventLogConfigPropertyStructDescribes the CloudWatch Logs configuration for the Event API.
CfnApi.LambdaAuthorizerConfigPropertyStructA LambdaAuthorizerConfig specifies how to authorize AWS AppSync API access when using the AWS_LAMBDA authorizer mode.
CfnApi.OpenIDConnectConfigPropertyStructDescribes an OpenID Connect (OIDC) configuration.
CfnApiCachePropsStructProperties for defining a CfnApiCache.
CfnApiKeyPropsStructProperties for defining a CfnApiKey.
CfnApiPropsStructProperties for defining a CfnApi.
CfnChannelNamespace.AuthModePropertyStructDescribes an authorization configuration.
CfnChannelNamespace.HandlerConfigPropertyStructThe HandlerConfig property type specifies the configuration for the handler.
CfnChannelNamespace.HandlerConfigsPropertyStructThe HandlerConfigs property type specifies the configuration for the OnPublish and OnSubscribe handlers.
CfnChannelNamespace.IntegrationPropertyStructThe Integration property type specifies the integration data source configuration for the handler.
CfnChannelNamespace.LambdaConfigPropertyStructThe LambdaConfig property type specifies the integration configuration for a Lambda data source.
CfnChannelNamespacePropsStructProperties for defining a CfnChannelNamespace.
CfnDataSource.AuthorizationConfigPropertyStructThe AuthorizationConfig property type specifies the authorization type and configuration for an AWS AppSync http data source.
CfnDataSource.AwsIamConfigPropertyStructUse the AwsIamConfig property type to specify AwsIamConfig for a AWS AppSync authorizaton.
CfnDataSource.DeltaSyncConfigPropertyStructDescribes a Delta Sync configuration.
CfnDataSource.DynamoDBConfigPropertyStructThe DynamoDBConfig property type specifies the AwsRegion and TableName for an Amazon DynamoDB table in your account for an AWS AppSync data source.
CfnDataSource.ElasticsearchConfigPropertyStruct
CfnDataSource.EventBridgeConfigPropertyStructThe data source.
CfnDataSource.HttpConfigPropertyStructUse the HttpConfig property type to specify HttpConfig for an AWS AppSync data source.
CfnDataSource.LambdaConfigPropertyStructThe LambdaConfig property type specifies the Lambda function ARN for an AWS AppSync data source.
CfnDataSource.OpenSearchServiceConfigPropertyStructThe OpenSearchServiceConfig property type specifies the AwsRegion and Endpoints for an Amazon OpenSearch Service domain in your account for an AWS AppSync data source.
CfnDataSource.RdsHttpEndpointConfigPropertyStructUse the RdsHttpEndpointConfig property type to specify the RdsHttpEndpoint for an AWS AppSync relational database.
CfnDataSource.RelationalDatabaseConfigPropertyStructUse the RelationalDatabaseConfig property type to specify RelationalDatabaseConfig for an AWS AppSync data source.
CfnDataSourcePropsStructProperties for defining a CfnDataSource.
CfnDomainNameApiAssociationPropsStructProperties for defining a CfnDomainNameApiAssociation.
CfnDomainNamePropsStructProperties for defining a CfnDomainName.
CfnFunctionConfiguration.AppSyncRuntimePropertyStructDescribes a runtime used by an AWS AppSync resolver or AWS AppSync function.
CfnFunctionConfiguration.LambdaConflictHandlerConfigPropertyStructThe LambdaConflictHandlerConfig object when configuring LAMBDA as the Conflict Handler.
CfnFunctionConfiguration.SyncConfigPropertyStructDescribes a Sync configuration for a resolver.
CfnFunctionConfigurationPropsStructProperties for defining a CfnFunctionConfiguration.
CfnGraphQLApi.AdditionalAuthenticationProviderPropertyStructDescribes an additional authentication provider.
CfnGraphQLApi.CognitoUserPoolConfigPropertyStructDescribes an Amazon Cognito user pool configuration.
CfnGraphQLApi.EnhancedMetricsConfigPropertyStructDescribes an enhanced metrics configuration.
CfnGraphQLApi.LambdaAuthorizerConfigPropertyStructConfiguration for AWS Lambda function authorization.
CfnGraphQLApi.LogConfigPropertyStructThe LogConfig property type specifies the logging configuration when writing GraphQL operations and tracing to Amazon CloudWatch for an AWS AppSync GraphQL API.
CfnGraphQLApi.OpenIDConnectConfigPropertyStructThe 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.UserPoolConfigPropertyStructThe UserPoolConfig property type specifies the optional authorization configuration for using Amazon Cognito user pools with your GraphQL endpoint for an AWS AppSync GraphQL API.
CfnGraphQLApiPropsStructProperties for defining a CfnGraphQLApi.
CfnGraphQLSchemaPropsStructProperties for defining a CfnGraphQLSchema.
CfnResolver.AppSyncRuntimePropertyStructDescribes a runtime used by an AWS AppSync resolver or AWS AppSync function.
CfnResolver.CachingConfigPropertyStructThe caching configuration for a resolver that has caching activated.
CfnResolver.LambdaConflictHandlerConfigPropertyStructThe LambdaConflictHandlerConfig when configuring LAMBDA as the Conflict Handler.
CfnResolver.PipelineConfigPropertyStructUse the PipelineConfig property type to specify PipelineConfig for an AWS AppSync resolver.
CfnResolver.SyncConfigPropertyStructDescribes a Sync configuration for a resolver.
CfnResolverPropsStructProperties for defining a CfnResolver.
CfnSourceApiAssociation.SourceApiAssociationConfigPropertyStructDescribes properties used to specify configurations related to a source API.
CfnSourceApiAssociationPropsStructProperties for defining a CfnSourceApiAssociation.
CfnTypePropsStructProperties for defining a CfnType.
ChannelNamespaceOptionsStructOption configuration for channel namespace.
ChannelNamespacePropsStructAdditional property for an AppSync channel namespace for an Event API reference.
CodeClassRepresents source code for an AppSync Function or Resolver.
CodeConfigStructResult of binding Code into a Function.
DataSourceLevelMetricsBehaviorEnumControls how data source metrics will be emitted to CloudWatch.
DataSourceMetricsConfigEnumEnum for enhanced data source metrics for specified data sources.
DataSourceOptionsStructOptional configuration for data sources.
DefinitionClassAppSync definition.
DomainOptionsStructDomain name configuration for AppSync.
DynamoDbDataSourceConstructAn AppSync datasource backed by a DynamoDB table.
DynamoDbDataSourcePropsStructProperties for an AppSync DynamoDB datasource.
ElasticsearchDataSourceConstructAn Appsync datasource backed by Elasticsearch.
ElasticsearchDataSourcePropsStructProperties for the Elasticsearch Data Source.
EnhancedMetricsConfigStructEnhanced metrics configuration for AppSync.
EventApiAttributesStructAttributes for Event API imports.
EventApiAuthConfigStructAuthorization configuration for the Event API.
EventApiPropsStructProperties for an AppSync Event API.
EventBridgeDataSourceConstructAn AppSync datasource backed by EventBridge.
EventBridgeDataSourcePropsStructProperties for an AppSync EventBridge datasource.
ExtendedDataSourcePropsStructprops used by implementations of BaseDataSource to provide configuration.
ExtendedResolverPropsStructAdditional property for an AppSync resolver for data source reference.
FieldLogLevelEnumlog-level for fields in AppSync.
FunctionRuntimeClassUtility class for specifying specific appsync runtime versions.
FunctionRuntimeFamilyEnumAppsync supported runtimes.
GraphqlApiAttributesStructAttributes for GraphQL imports.
GraphqlApiPropsStructProperties for an AppSync GraphQL API.
HandlerBehaviorEnumEnumerated type for the handler behavior for a channel namespace.
HandlerConfigStructHandler configuration construct for onPublish and onSubscribe.
HttpDataSourceConstructAn AppSync datasource backed by a http endpoint.
HttpDataSourceOptionsStructOptional configuration for Http data sources.
HttpDataSourcePropsStructProperties for an AppSync http datasource.
IamResourceClassA class used to generate resource arns for AppSync.
IApiInterfaceInterface for an API.
IAppSyncAuthConfigInterfaceExposes methods for defining authorization config for AppSync APIs.
IAppsyncFunctionInterfaceInterface for AppSync Functions.
IChannelNamespaceInterfaceAn AppSync channel namespace.
IEventApiInterfaceInterface for Event API.
IGraphqlApiInterfaceInterface for GraphQL.
InlineCodeClassAppSync function code from an inline string.
IntrospectionConfigEnumIntrospection configuration for a GraphQL API.
ISchemaInterfaceInterface for implementing your own schema.
ISchemaConfigInterfaceConfiguration for bound graphql schema.
ISourceApiAssociationInterfaceInterface for AppSync Source Api Association.
KeyConditionClassFactory class for DynamoDB key conditions.
LambdaAuthorizerConfigStructConfiguration for Lambda authorization in AppSync.
LambdaDataSourceConstructAn AppSync datasource backed by a Lambda function.
LambdaDataSourcePropsStructProperties for an AppSync Lambda datasource.
LambdaInvokeTypeEnumInvoke types for direct Lambda data sources.
LogConfigStructLogging configuration for AppSync.
MappingTemplateClassMappingTemplates for AppSync resolvers.
MergeTypeEnumMerge type used to associate the source API.
NamespaceAuthConfigStructAuthorization configuration for the Channel Namespace.
NoneDataSourceConstructAn AppSync dummy datasource.
NoneDataSourcePropsStructProperties for an AppSync dummy datasource.
OpenIdConnectConfigStructConfiguration for OpenID Connect authorization in AppSync.
OpenSearchDataSourceConstructAn Appsync datasource backed by OpenSearch.
OpenSearchDataSourcePropsStructProperties for the OpenSearch Data Source.
OperationLevelMetricsConfigEnumControls how operation metrics will be emitted to CloudWatch.
PartitionKeyClassSpecifies the assignment to the partition key.
PartitionKeyStepClassUtility class to allow assigning a value or an auto-generated id to a partition key.
PrimaryKeyClassSpecifies the assignment to the primary key.
RdsDataSourceConstructAn AppSync datasource backed by RDS.
RdsDataSourcePropsStructProperties for an AppSync RDS datasource Aurora Serverless V1.
RdsDataSourcePropsV2StructProperties for an AppSync RDS datasource Aurora Serverless V2.
ResolverConstructAn AppSync resolver.
ResolverLevelMetricsBehaviorEnumControls how resolver metrics will be emitted to CloudWatch.
ResolverMetricsConfigEnumEnum for enhanced resolver metrics for specified resolvers.
ResolverPropsStructAdditional property for an AppSync resolver for GraphQL API reference.
RuntimeConfigStructConfig for binding runtime to a function or resolver.
SchemaBindOptionsStructUsed for configuring schema bind behavior.
SchemaFileClassThe Schema for a GraphQL Api.
SchemaPropsStructThe options for configuring a schema from an existing file.
SortKeyStepClassUtility class to allow assigning a value or an auto-generated id to a sort key.
SourceApiStructConfiguration of source API.
SourceApiAssociationAttributesStructThe attributes for imported AppSync Source Api Association.
SourceApiAssociationPropsStructProperties for SourceApiAssociation which associates an AppSync Source API with an AppSync Merged API.
SourceApiOptionsStructAdditional API configuration for creating a AppSync Merged API.
UserPoolConfigStructConfiguration for Cognito user-pools in AppSync.
UserPoolDefaultActionEnumenum with all possible values for Cognito user-pool default actions.
ValuesClassFactory class for attribute value assignments.
VisibilityEnumVisibility type for a GraphQL API.