# AWS AppSync Construct Library

The `aws-cdk-lib/aws-appsync` package contains constructs for building flexible
APIs that use [GraphQL](https://docs.aws.amazon.com/appsync/latest/devguide/what-is-appsync.html) and [Events](https://docs.aws.amazon.com/appsync/latest/eventapi/event-api-welcome.html).

TypeScript:

```ts
import * as appsync from 'aws-cdk-lib/aws-appsync';
```

Python:

```python
import aws_cdk.aws_appsync as appsync
```

Java:

```java
import software.amazon.awscdk.services.appsync.*;
```

C# / .NET:

```csharp
using Amazon.CDK.AWS.AppSync;
```

Golang:

```go
import appsync "github.com/aws/aws-cdk-go/awscdk"
```

## GraphQL

### Example

#### DynamoDB

Example of a GraphQL API with `AWS_IAM` [authorization](#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`:

TypeScript:

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

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

```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());
```

C# / .NET:

```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()
});
```

Golang:

```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

TypeScript:

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

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

```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());
```

C# / .NET:

```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])
      ")
});
```

Golang:

```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

TypeScript:

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

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

```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());
```

C# / .NET:

```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])
      ")
});
```

Golang:

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

TypeScript:

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

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

```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());
```

C# / .NET:

```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")
});
```

Golang:

```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](https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutEvents.html).
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](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-eventbridge.html).

CDK stack file `app-stack.ts`:

TypeScript:

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

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

```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());
```

C# / .NET:

```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")
});
```

Golang:

```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.

TypeScript:

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

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

```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());
```

C# / .NET:

```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
      ]")
});
```

Golang:

```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](https://docs.aws.amazon.com/appsync/latest/devguide/merged-api.html) which can be used to merge multiple source APIs into a single API.

TypeScript:

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

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

```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();
```

C# / .NET:

```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
        } }
    })
});
```

Golang:

```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.

TypeScript:

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

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

```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();
```

C# / .NET:

```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
});
```

Golang:

```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](https://github.com/cdklabs/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.

TypeScript:

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

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

```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();
```

C# / .NET:

```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
});
```

Golang:

```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](https://docs.aws.amazon.com/en_us/appsync/latest/devguide/monitoring.html#cwl).

To obtain the GraphQL API's log group as a `logs.ILogGroup` use the `logGroup` property of the
[`GraphqlApi`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.GraphqlApi.html) construct.

TypeScript:

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

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

```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();
```

C# / .NET:

```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
    }
});
```

Golang:

```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`

TypeScript:

```ts
const api = new appsync.GraphqlApi(this, 'api', {
  name: 'myApi',
  definition: appsync.Definition.fromFile(path.join(__dirname, 'schema.graphl')),
});
```

Python:

```python
api = appsync.GraphqlApi(self, "api",
    name="myApi",
    definition=appsync.Definition.from_file(path.join(__dirname, "schema.graphl"))
)
```

Java:

```java
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
        .name("myApi")
        .definition(Definition.fromFile(join(__dirname, "schema.graphl")))
        .build();
```

C# / .NET:

```csharp
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "myApi",
    Definition = Definition.FromFile(Join(__dirname, "schema.graphl"))
});
```

Golang:

```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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ISchema.html)
interface. An example of this is the `CodeFirstSchema` class provided in
[awscdk-appsync-utils](https://github.com/cdklabs/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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.IGraphqlApi.html) interface.

TypeScript:

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

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

```java
GraphqlApi api;
Table table;

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

C# / .NET:

```csharp
GraphqlApi api;
Table table;

var importedApi = GraphqlApi.FromGraphqlApiAttributes(this, "IApi", new GraphqlApiAttributes {
    GraphqlApiId = api.ApiId,
    GraphqlApiArn = api.Arn
});
importedApi.AddDynamoDbDataSource("TableDataSource", table);
```

Golang:

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

TypeScript:

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

```python
api = appsync.GraphqlApi(self, "api",
    name="MyPrivateAPI",
    definition=appsync.Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
    visibility=appsync.Visibility.PRIVATE
)
```

Java:

```java
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
        .name("MyPrivateAPI")
        .definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
        .visibility(Visibility.PRIVATE)
        .build();
```

C# / .NET:

```csharp
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "MyPrivateAPI",
    Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
    Visibility = Visibility.PRIVATE
});
```

Golang:

```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](https://docs.aws.amazon.com/appsync/latest/devguide/using-private-apis.html)
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.

TypeScript:

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

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

```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();
```

C# / .NET:

```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
            }
        }
    }
});
```

Golang:

```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](https://docs.aws.amazon.com/appsync/latest/devguide/security.html#aws-iam-authorization) for more details.

To make this easier, CDK provides `grant` API.

Use the `grant` function for more granular authorization.

TypeScript:

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

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

```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");
```

C# / .NET:

```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");
```

Golang:

```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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.IamResource.html).

- `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)

TypeScript:

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

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

```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");
```

C# / .NET:

```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");
```

Golang:

```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.

TypeScript:

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

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

```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();
```

C# / .NET:

```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")
});
```

Golang:

```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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.LambdaDataSource.html), 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.

TypeScript:

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

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

```java
GraphqlApi api;
LambdaDataSource lambdaDataSource;

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

C# / .NET:

```csharp
GraphqlApi api;
LambdaDataSource lambdaDataSource;

var appsyncFunction = new AppsyncFunction(this, "function", new AppsyncFunctionProps {
    Name = "appsync_function",
    Api = api,
    DataSource = lambdaDataSource,
    MaxBatchSize = 10
});
```

Golang:

```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.

TypeScript:

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

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

```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();
```

C# / .NET:

```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")
});
```

Golang:

```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.

TypeScript:

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

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

```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();
```

C# / .NET:

```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 }
});
```

Golang:

```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](https://docs.aws.amazon.com/appsync/latest/devguide/pipeline-resolvers.html).

### 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`.

TypeScript:

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

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

```java
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
        .name("DisableIntrospectionApi")
        .definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
        .introspectionConfig(IntrospectionConfig.DISABLED)
        .build();
```

C# / .NET:

```csharp
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "DisableIntrospectionApi",
    Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
    IntrospectionConfig = IntrospectionConfig.DISABLED
});
```

Golang:

```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.

TypeScript:

```ts
const api = new appsync.GraphqlApi(this, 'api', {
  name: 'LimitQueryDepths',
  definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.schema.graphql')),
  queryDepthLimit: 2,
});
```

Python:

```python
api = appsync.GraphqlApi(self, "api",
    name="LimitQueryDepths",
    definition=appsync.Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
    query_depth_limit=2
)
```

Java:

```java
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
        .name("LimitQueryDepths")
        .definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
        .queryDepthLimit(2)
        .build();
```

C# / .NET:

```csharp
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "LimitQueryDepths",
    Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
    QueryDepthLimit = 2
});
```

Golang:

```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.

TypeScript:

```ts
const api = new appsync.GraphqlApi(this, 'api', {
  name: 'LimitResolverCount',
  definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.schema.graphql')),
  resolverCountLimit: 2,
});
```

Python:

```python
api = appsync.GraphqlApi(self, "api",
    name="LimitResolverCount",
    definition=appsync.Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
    resolver_count_limit=2
)
```

Java:

```java
GraphqlApi api = GraphqlApi.Builder.create(this, "api")
        .name("LimitResolverCount")
        .definition(Definition.fromFile(join(__dirname, "appsync.schema.graphql")))
        .resolverCountLimit(2)
        .build();
```

C# / .NET:

```csharp
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "LimitResolverCount",
    Definition = Definition.FromFile(Join(__dirname, "appsync.schema.graphql")),
    ResolverCountLimit = 2
});
```

Golang:

```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.

TypeScript:

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

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

```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");
```

C# / .NET:

```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");
```

Golang:

```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.

TypeScript:

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

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

```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());
```

C# / .NET:

```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" }
    })
}));
```

Golang:

```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.

TypeScript:

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

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

```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();
```

C# / .NET:

```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"
});
```

Golang:

```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.

TypeScript:

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

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

```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();
```

C# / .NET:

```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
    }
});
```

Golang:

```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.

TypeScript:

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

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

```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());
```

C# / .NET:

```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
});
```

Golang:

```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.

TypeScript:

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

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

```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");
```

C# / .NET:

```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");
```

Golang:

```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](https://docs.aws.amazon.com/appsync/latest/eventapi/configure-event-api-auth.html).

TypeScript:

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

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

```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");
```

C# / .NET:

```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");
```

Golang:

```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.

TypeScript:

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

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

```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");
```

C# / .NET:

```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");
```

Golang:

```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

TypeScript:

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

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

```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);
```

C# / .NET:

```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);
```

Golang:

```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

TypeScript:

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

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

```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);
```

C# / .NET:

```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);
```

Golang:

```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

TypeScript:

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

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

```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);
```

C# / .NET:

```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);
```

Golang:

```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

TypeScript:

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

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

```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);
```

C# / .NET:

```csharp
using Amazon.CDK.AWS.Lambda;

Function lambdaDs;

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

var dataSource = api.AddLambdaDataSource("lambdads", lambdaDs);
```

Golang:

```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

TypeScript:

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

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

```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);
```

C# / .NET:

```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);
```

Golang:

```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

TypeScript:

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

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

```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));
```

C# / .NET:

```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");
```

Golang:

```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](https://docs.aws.amazon.com/appsync/latest/eventapi/event-api-custom-domains.html).

TypeScript:

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

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

```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();
```

C# / .NET:

```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 });
```

Golang:

```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](https://docs.aws.amazon.com/appsync/latest/eventapi/event-api-monitoring-cw-logs.html).

To obtain the Event API's log group as a `logs.ILogGroup` use the `logGroup` property of the
`Api` construct.

TypeScript:

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

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

```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");
```

C# / .NET:

```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");
```

Golang:

```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](https://docs.aws.amazon.com/appsync/latest/eventapi/using-waf-protect-apis.html).

TypeScript:

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

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

```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();
```

C# / .NET:

```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
});
```

Golang:

```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](https://docs.aws.amazon.com/appsync/latest/eventapi/channel-namespaces.html).

TypeScript:

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

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

```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());
```

C# / .NET:

```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 { });
```

Golang:

```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.

TypeScript:

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

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

```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();
```

C# / .NET:

```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 }
    }
});
```

Golang:

```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](https://docs.aws.amazon.com/appsync/latest/eventapi/channel-namespace-handlers.html).

TypeScript:

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

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

```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();
```

C# / .NET:

```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")
});
```

Golang:

```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

TypeScript:

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

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

```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());
```

C# / .NET:

```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
    }
});
```

Golang:

```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

TypeScript:

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

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

```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());
```

C# / .NET:

```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
    }
});
```

Golang:

```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

### Constructs (L2)

- [`ApiBase`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ApiBase.html) Construct (L2) Base Class for API.
- [`AppsyncFunction`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppsyncFunction.html) Construct (L2) AppSync Functions are local functions that perform certain operations onto a backend data source.
- [`ChannelNamespace`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ChannelNamespace.html) Construct (L2) A Channel Namespace.
- [`EventApi`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.EventApi.html) Construct (L2) An AppSync Event API.
- [`EventApiBase`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.EventApiBase.html) Construct (L2) Base Class for Event API.
- [`GraphqlApi`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.GraphqlApi.html) Construct (L2) An AppSync GraphQL API.
- [`GraphqlApiBase`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.GraphqlApiBase.html) Construct (L2) Base Class for GraphQL API.
- [`SourceApiAssociation`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.SourceApiAssociation.html) Construct (L2) AppSync SourceApiAssociation which associates an AppSync source API to an AppSync Merged API.

### Constructs (L1)

- [`CfnApi`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApi.html) Construct (L1) The `AWS::AppSync::Api` resource creates an AWS AppSync API that you can use for an AWS AppSync API with your preferred configuration, such as an Event API that provides real-time message publishing and message subscriptions over WebSockets.
- [`CfnApiCache`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApiCache.html) Construct (L1) The `AWS::AppSync::ApiCache` resource represents the input of a `CreateApiCache` operation.
- [`CfnApiKey`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApiKey.html) Construct (L1) The `AWS::AppSync::ApiKey` resource creates a unique key that you can distribute to clients who are executing GraphQL operations with AWS AppSync that require an API key.
- [`CfnChannelNamespace`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnChannelNamespace.html) Construct (L1) The `AWS::AppSync::ChannelNamespace` resource creates a channel namespace associated with an `Api` .
- [`CfnDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSource.html) Construct (L1) The `AWS::AppSync::DataSource` resource creates data sources for resolvers in AWS AppSync to connect to, such as Amazon DynamoDB , AWS Lambda , and Amazon OpenSearch Service .
- [`CfnDomainName`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDomainName.html) Construct (L1) The `AWS::AppSync::DomainName` resource creates a `DomainNameConfig` object to configure a custom domain.
- [`CfnDomainNameApiAssociation`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDomainNameApiAssociation.html) Construct (L1) The `AWS::AppSync::DomainNameApiAssociation` resource represents the mapping of your custom domain name to the assigned API URL.
- [`CfnFunctionConfiguration`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnFunctionConfiguration.html) Construct (L1) The `AWS::AppSync::FunctionConfiguration` resource defines the functions in GraphQL APIs to perform certain operations.
- [`CfnGraphQLApi`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnGraphQLApi.html) Construct (L1) The `AWS::AppSync::GraphQLApi` resource creates a new AWS AppSync GraphQL API.
- [`CfnGraphQLSchema`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnGraphQLSchema.html) Construct (L1) The `AWS::AppSync::GraphQLSchema` resource is used for your AWS AppSync GraphQL schema that controls the data model for your API.
- [`CfnResolver`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnResolver.html) Construct (L1) The `AWS::AppSync::Resolver` resource defines the logical GraphQL resolver that you attach to fields in a schema.
- [`CfnSourceApiAssociation`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnSourceApiAssociation.html) Construct (L1) Describes the configuration of a source API.
- [`CfnType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnType.html) Construct (L1) Represents a GraphQL type in an AWS AppSync GraphQL API.

### Structs

- [`ApiKeyConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ApiKeyConfig.html) Struct Configuration for API Key authorization in AppSync.
- [`AppSyncApiKeyConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncApiKeyConfig.html) Struct Configuration for API Key authorization in AppSync.
- [`AppSyncAuthProvider`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncAuthProvider.html) Struct Auth provider settings for AppSync Event APIs.
- [`AppSyncAwsIamConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncAwsIamConfig.html) Struct The authorization config in case the HTTP endpoint requires authorization.
- [`AppSyncBackedDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncBackedDataSourceProps.html) Struct Properties for an AppSync datasource backed by a resource.
- [`AppSyncBaseDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncBaseDataSourceProps.html) Struct Base properties for an AppSync datasource.
- [`AppSyncCognitoConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncCognitoConfig.html) Struct Configuration for Cognito user-pools in AppSync for Api.
- [`AppSyncDataSourceOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncDataSourceOptions.html) Struct Optional configuration for data sources.
- [`AppSyncDomainOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncDomainOptions.html) Struct Domain name configuration for AppSync.
- [`AppSyncDynamoDbDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncDynamoDbDataSourceProps.html) Struct Properties for an AppSync DynamoDB datasource.
- [`AppSyncEventBridgeDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncEventBridgeDataSourceProps.html) Struct Properties for an AppSync EventBridge datasource.
- [`AppSyncExtendedDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncExtendedDataSourceProps.html) Struct Props used by implementations of BaseDataSource to provide configuration.
- [`AppsyncFunctionAttributes`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppsyncFunctionAttributes.html) Struct The attributes for imported AppSync Functions.
- [`AppsyncFunctionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppsyncFunctionProps.html) Struct the CDK properties for AppSync Functions.
- [`AppSyncHttpDataSourceOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncHttpDataSourceOptions.html) Struct Optional configuration for Http data sources.
- [`AppSyncHttpDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncHttpDataSourceProps.html) Struct Properties for an AppSync http datasource.
- [`AppSyncLambdaAuthorizerConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncLambdaAuthorizerConfig.html) Struct Configuration for Lambda authorization in AppSync.
- [`AppSyncLambdaDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncLambdaDataSourceProps.html) Struct Properties for an AppSync Lambda datasource.
- [`AppSyncLogConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncLogConfig.html) Struct Logging configuration for AppSync.
- [`AppSyncOpenIdConnectConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncOpenIdConnectConfig.html) Struct Configuration for OpenID Connect authorization in AppSync.
- [`AppSyncOpenSearchDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncOpenSearchDataSourceProps.html) Struct Properties for the OpenSearch Data Source.
- [`AppSyncRdsDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncRdsDataSourceProps.html) Struct Properties for an AppSync RDS datasource Aurora Serverless V1.
- [`AppSyncRdsDataSourcePropsV2`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncRdsDataSourcePropsV2.html) Struct Properties for an AppSync RDS datasource Aurora Serverless V2.
- [`AuthorizationConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AuthorizationConfig.html) Struct Configuration of the API authorization modes.
- [`AuthorizationMode`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AuthorizationMode.html) Struct Interface to specify default or additional authorization(s).
- [`AwsIamConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AwsIamConfig.html) Struct The authorization config in case the HTTP endpoint requires authorization.
- [`BackedDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.BackedDataSourceProps.html) Struct properties for an AppSync datasource backed by a resource.
- [`BaseAppsyncFunctionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.BaseAppsyncFunctionProps.html) Struct the base properties for AppSync Functions.
- [`BaseChannelNamespaceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.BaseChannelNamespaceProps.html) Struct the base properties for a channel namespace.
- [`BaseDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.BaseDataSourceProps.html) Struct Base properties for an AppSync datasource.
- [`BaseResolverProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.BaseResolverProps.html) Struct Basic properties for an AppSync resolver.
- [`CachingConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CachingConfig.html) Struct CachingConfig for AppSync resolvers.
- [`CfnApi.AuthModeProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApi.AuthModeProperty.html) Struct Describes an authorization configuration.
- [`CfnApi.AuthProviderProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApi.AuthProviderProperty.html) Struct Describes an authorization provider.
- [`CfnApi.CognitoConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApi.CognitoConfigProperty.html) Struct Describes an Amazon Cognito configuration.
- [`CfnApi.DnsMapProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApi.DnsMapProperty.html) Struct A map of DNS names for the Api.
- [`CfnApi.EventConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApi.EventConfigProperty.html) Struct Describes the authorization configuration for connections, message publishing, message subscriptions, and logging for an Event API.
- [`CfnApi.EventLogConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApi.EventLogConfigProperty.html) Struct Describes the CloudWatch Logs configuration for the Event API.
- [`CfnApi.LambdaAuthorizerConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApi.LambdaAuthorizerConfigProperty.html) Struct A `LambdaAuthorizerConfig` specifies how to authorize AWS AppSync API access when using the `AWS_LAMBDA` authorizer mode.
- [`CfnApi.OpenIDConnectConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApi.OpenIDConnectConfigProperty.html) Struct Describes an OpenID Connect (OIDC) configuration.
- [`CfnApiCacheProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApiCacheProps.html) Struct Properties for defining a `CfnApiCache`.
- [`CfnApiKeyProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApiKeyProps.html) Struct Properties for defining a `CfnApiKey`.
- [`CfnApiProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnApiProps.html) Struct Properties for defining a `CfnApi`.
- [`CfnChannelNamespace.AuthModeProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnChannelNamespace.AuthModeProperty.html) Struct Describes an authorization configuration.
- [`CfnChannelNamespace.HandlerConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnChannelNamespace.HandlerConfigProperty.html) Struct The `HandlerConfig` property type specifies the configuration for the handler.
- [`CfnChannelNamespace.HandlerConfigsProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnChannelNamespace.HandlerConfigsProperty.html) Struct The `HandlerConfigs` property type specifies the configuration for the `OnPublish` and `OnSubscribe` handlers.
- [`CfnChannelNamespace.IntegrationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnChannelNamespace.IntegrationProperty.html) Struct The `Integration` property type specifies the integration data source configuration for the handler.
- [`CfnChannelNamespace.LambdaConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnChannelNamespace.LambdaConfigProperty.html) Struct The `LambdaConfig` property type specifies the integration configuration for a Lambda data source.
- [`CfnChannelNamespaceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnChannelNamespaceProps.html) Struct Properties for defining a `CfnChannelNamespace`.
- [`CfnDataSource.AuthorizationConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSource.AuthorizationConfigProperty.html) Struct The `AuthorizationConfig` property type specifies the authorization type and configuration for an AWS AppSync http data source.
- [`CfnDataSource.AwsIamConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSource.AwsIamConfigProperty.html) Struct Use the `AwsIamConfig` property type to specify `AwsIamConfig` for a AWS AppSync authorizaton.
- [`CfnDataSource.DeltaSyncConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSource.DeltaSyncConfigProperty.html) Struct Describes a Delta Sync configuration.
- [`CfnDataSource.DynamoDBConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSource.DynamoDBConfigProperty.html) Struct The `DynamoDBConfig` property type specifies the `AwsRegion` and `TableName` for an Amazon DynamoDB table in your account for an AWS AppSync data source.
- [`CfnDataSource.ElasticsearchConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSource.ElasticsearchConfigProperty.html) Struct
- [`CfnDataSource.EventBridgeConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSource.EventBridgeConfigProperty.html) Struct The data source.
- [`CfnDataSource.HttpConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSource.HttpConfigProperty.html) Struct Use the `HttpConfig` property type to specify `HttpConfig` for an AWS AppSync data source.
- [`CfnDataSource.LambdaConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSource.LambdaConfigProperty.html) Struct The `LambdaConfig` property type specifies the Lambda function ARN for an AWS AppSync data source.
- [`CfnDataSource.OpenSearchServiceConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSource.OpenSearchServiceConfigProperty.html) Struct The `OpenSearchServiceConfig` property type specifies the `AwsRegion` and `Endpoints` for an Amazon OpenSearch Service domain in your account for an AWS AppSync data source.
- [`CfnDataSource.RdsHttpEndpointConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSource.RdsHttpEndpointConfigProperty.html) Struct Use the `RdsHttpEndpointConfig` property type to specify the `RdsHttpEndpoint` for an AWS AppSync relational database.
- [`CfnDataSource.RelationalDatabaseConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSource.RelationalDatabaseConfigProperty.html) Struct Use the `RelationalDatabaseConfig` property type to specify `RelationalDatabaseConfig` for an AWS AppSync data source.
- [`CfnDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDataSourceProps.html) Struct Properties for defining a `CfnDataSource`.
- [`CfnDomainNameApiAssociationProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDomainNameApiAssociationProps.html) Struct Properties for defining a `CfnDomainNameApiAssociation`.
- [`CfnDomainNameProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnDomainNameProps.html) Struct Properties for defining a `CfnDomainName`.
- [`CfnFunctionConfiguration.AppSyncRuntimeProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnFunctionConfiguration.AppSyncRuntimeProperty.html) Struct Describes a runtime used by an AWS AppSync resolver or AWS AppSync function.
- [`CfnFunctionConfiguration.LambdaConflictHandlerConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnFunctionConfiguration.LambdaConflictHandlerConfigProperty.html) Struct The `LambdaConflictHandlerConfig` object when configuring `LAMBDA` as the Conflict Handler.
- [`CfnFunctionConfiguration.SyncConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnFunctionConfiguration.SyncConfigProperty.html) Struct Describes a Sync configuration for a resolver.
- [`CfnFunctionConfigurationProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnFunctionConfigurationProps.html) Struct Properties for defining a `CfnFunctionConfiguration`.
- [`CfnGraphQLApi.AdditionalAuthenticationProviderProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnGraphQLApi.AdditionalAuthenticationProviderProperty.html) Struct Describes an additional authentication provider.
- [`CfnGraphQLApi.CognitoUserPoolConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnGraphQLApi.CognitoUserPoolConfigProperty.html) Struct Describes an Amazon Cognito user pool configuration.
- [`CfnGraphQLApi.EnhancedMetricsConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnGraphQLApi.EnhancedMetricsConfigProperty.html) Struct Describes an enhanced metrics configuration.
- [`CfnGraphQLApi.LambdaAuthorizerConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnGraphQLApi.LambdaAuthorizerConfigProperty.html) Struct Configuration for AWS Lambda function authorization.
- [`CfnGraphQLApi.LogConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnGraphQLApi.LogConfigProperty.html) Struct The `LogConfig` property type specifies the logging configuration when writing GraphQL operations and tracing to Amazon CloudWatch for an AWS AppSync GraphQL API.
- [`CfnGraphQLApi.OpenIDConnectConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnGraphQLApi.OpenIDConnectConfigProperty.html) Struct The `OpenIDConnectConfig` property type specifies the optional authorization configuration for using an OpenID Connect compliant service with your GraphQL endpoint for an AWS AppSync GraphQL API.
- [`CfnGraphQLApi.UserPoolConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnGraphQLApi.UserPoolConfigProperty.html) Struct The `UserPoolConfig` property type specifies the optional authorization configuration for using Amazon Cognito user pools with your GraphQL endpoint for an AWS AppSync GraphQL API.
- [`CfnGraphQLApiProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnGraphQLApiProps.html) Struct Properties for defining a `CfnGraphQLApi`.
- [`CfnGraphQLSchemaProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnGraphQLSchemaProps.html) Struct Properties for defining a `CfnGraphQLSchema`.
- [`CfnResolver.AppSyncRuntimeProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnResolver.AppSyncRuntimeProperty.html) Struct Describes a runtime used by an AWS AppSync resolver or AWS AppSync function.
- [`CfnResolver.CachingConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnResolver.CachingConfigProperty.html) Struct The caching configuration for a resolver that has caching activated.
- [`CfnResolver.LambdaConflictHandlerConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnResolver.LambdaConflictHandlerConfigProperty.html) Struct The `LambdaConflictHandlerConfig` when configuring LAMBDA as the Conflict Handler.
- [`CfnResolver.PipelineConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnResolver.PipelineConfigProperty.html) Struct Use the `PipelineConfig` property type to specify `PipelineConfig` for an AWS AppSync resolver.
- [`CfnResolver.SyncConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnResolver.SyncConfigProperty.html) Struct Describes a Sync configuration for a resolver.
- [`CfnResolverProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnResolverProps.html) Struct Properties for defining a `CfnResolver`.
- [`CfnSourceApiAssociation.SourceApiAssociationConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnSourceApiAssociation.SourceApiAssociationConfigProperty.html) Struct Describes properties used to specify configurations related to a source API.
- [`CfnSourceApiAssociationProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnSourceApiAssociationProps.html) Struct Properties for defining a `CfnSourceApiAssociation`.
- [`CfnTypeProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnTypeProps.html) Struct Properties for defining a `CfnType`.
- [`ChannelNamespaceOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ChannelNamespaceOptions.html) Struct Option configuration for channel namespace.
- [`ChannelNamespaceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ChannelNamespaceProps.html) Struct Additional property for an AppSync channel namespace for an Event API reference.
- [`CodeConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CodeConfig.html) Struct Result of binding `Code` into a `Function`.
- [`DataSourceOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.DataSourceOptions.html) Struct Optional configuration for data sources.
- [`DomainOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.DomainOptions.html) Struct Domain name configuration for AppSync.
- [`DynamoDbDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.DynamoDbDataSourceProps.html) Struct Properties for an AppSync DynamoDB datasource.
- [`ElasticsearchDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ElasticsearchDataSourceProps.html) Struct Properties for the Elasticsearch Data Source.
- [`EnhancedMetricsConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.EnhancedMetricsConfig.html) Struct Enhanced metrics configuration for AppSync.
- [`EventApiAttributes`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.EventApiAttributes.html) Struct Attributes for Event API imports.
- [`EventApiAuthConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.EventApiAuthConfig.html) Struct Authorization configuration for the Event API.
- [`EventApiProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.EventApiProps.html) Struct Properties for an AppSync Event API.
- [`EventBridgeDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.EventBridgeDataSourceProps.html) Struct Properties for an AppSync EventBridge datasource.
- [`ExtendedDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ExtendedDataSourceProps.html) Struct props used by implementations of BaseDataSource to provide configuration.
- [`ExtendedResolverProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ExtendedResolverProps.html) Struct Additional property for an AppSync resolver for data source reference.
- [`GraphqlApiAttributes`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.GraphqlApiAttributes.html) Struct Attributes for GraphQL imports.
- [`GraphqlApiProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.GraphqlApiProps.html) Struct Properties for an AppSync GraphQL API.
- [`HandlerConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.HandlerConfig.html) Struct Handler configuration construct for onPublish and onSubscribe.
- [`HttpDataSourceOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.HttpDataSourceOptions.html) Struct Optional configuration for Http data sources.
- [`HttpDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.HttpDataSourceProps.html) Struct Properties for an AppSync http datasource.
- [`LambdaAuthorizerConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.LambdaAuthorizerConfig.html) Struct Configuration for Lambda authorization in AppSync.
- [`LambdaDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.LambdaDataSourceProps.html) Struct Properties for an AppSync Lambda datasource.
- [`LogConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.LogConfig.html) Struct Logging configuration for AppSync.
- [`NamespaceAuthConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.NamespaceAuthConfig.html) Struct Authorization configuration for the Channel Namespace.
- [`NoneDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.NoneDataSourceProps.html) Struct Properties for an AppSync dummy datasource.
- [`OpenIdConnectConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.OpenIdConnectConfig.html) Struct Configuration for OpenID Connect authorization in AppSync.
- [`OpenSearchDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.OpenSearchDataSourceProps.html) Struct Properties for the OpenSearch Data Source.
- [`RdsDataSourceProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.RdsDataSourceProps.html) Struct Properties for an AppSync RDS datasource Aurora Serverless V1.
- [`RdsDataSourcePropsV2`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.RdsDataSourcePropsV2.html) Struct Properties for an AppSync RDS datasource Aurora Serverless V2.
- [`ResolverProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ResolverProps.html) Struct Additional property for an AppSync resolver for GraphQL API reference.
- [`RuntimeConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.RuntimeConfig.html) Struct Config for binding runtime to a function or resolver.
- [`SchemaBindOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.SchemaBindOptions.html) Struct Used for configuring schema bind behavior.
- [`SchemaProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.SchemaProps.html) Struct The options for configuring a schema from an existing file.
- [`SourceApi`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.SourceApi.html) Struct Configuration of source API.
- [`SourceApiAssociationAttributes`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.SourceApiAssociationAttributes.html) Struct The attributes for imported AppSync Source Api Association.
- [`SourceApiAssociationProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.SourceApiAssociationProps.html) Struct Properties for SourceApiAssociation which associates an AppSync Source API with an AppSync Merged API.
- [`SourceApiOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.SourceApiOptions.html) Struct Additional API configuration for creating a AppSync Merged API.
- [`UserPoolConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.UserPoolConfig.html) Struct Configuration for Cognito user-pools in AppSync.

### Enums

- [`AppSyncAuthorizationType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncAuthorizationType.html) Enum enum with all possible values for AppSync authorization type.
- [`AppSyncDataSourceType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncDataSourceType.html) Enum Valid data source types for AppSync.
- [`AppSyncFieldLogLevel`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncFieldLogLevel.html) Enum log-level for fields in AppSync.
- [`AuthorizationType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AuthorizationType.html) Enum enum with all possible values for AppSync authorization type.
- [`DataSourceLevelMetricsBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.DataSourceLevelMetricsBehavior.html) Enum Controls how data source metrics will be emitted to CloudWatch.
- [`DataSourceMetricsConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.DataSourceMetricsConfig.html) Enum Enum for enhanced data source metrics for specified data sources.
- [`FieldLogLevel`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.FieldLogLevel.html) Enum log-level for fields in AppSync.
- [`FunctionRuntimeFamily`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.FunctionRuntimeFamily.html) Enum Appsync supported runtimes.
- [`HandlerBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.HandlerBehavior.html) Enum Enumerated type for the handler behavior for a channel namespace.
- [`IntrospectionConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.IntrospectionConfig.html) Enum Introspection configuration for a GraphQL API.
- [`LambdaInvokeType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.LambdaInvokeType.html) Enum Invoke types for direct Lambda data sources.
- [`MergeType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.MergeType.html) Enum Merge type used to associate the source API.
- [`OperationLevelMetricsConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.OperationLevelMetricsConfig.html) Enum Controls how operation metrics will be emitted to CloudWatch.
- [`ResolverLevelMetricsBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ResolverLevelMetricsBehavior.html) Enum Controls how resolver metrics will be emitted to CloudWatch.
- [`ResolverMetricsConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ResolverMetricsConfig.html) Enum Enum for enhanced resolver metrics for specified resolvers.
- [`UserPoolDefaultAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.UserPoolDefaultAction.html) Enum enum with all possible values for Cognito user-pool default actions.
- [`Visibility`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.Visibility.html) Enum Visibility type for a GraphQL API.

### Constructs

- [`AppSyncBackedDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncBackedDataSource.html) Construct Abstract AppSync datasource implementation.
- [`AppSyncBaseDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncBaseDataSource.html) Construct Abstract AppSync datasource implementation.
- [`AppSyncDynamoDbDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncDynamoDbDataSource.html) Construct An AppSync datasource backed by a DynamoDB table.
- [`AppSyncEventBridgeDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncEventBridgeDataSource.html) Construct An AppSync datasource backed by EventBridge.
- [`AppSyncHttpDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncHttpDataSource.html) Construct An AppSync datasource backed by a http endpoint.
- [`AppSyncLambdaDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncLambdaDataSource.html) Construct An AppSync datasource backed by a Lambda function.
- [`AppSyncOpenSearchDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncOpenSearchDataSource.html) Construct An Appsync datasource backed by OpenSearch.
- [`AppSyncRdsDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncRdsDataSource.html) Construct An AppSync datasource backed by RDS.
- [`BackedDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.BackedDataSource.html) Construct Abstract AppSync datasource implementation.
- [`BaseDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.BaseDataSource.html) Construct Abstract AppSync datasource implementation.
- [`DynamoDbDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.DynamoDbDataSource.html) Construct An AppSync datasource backed by a DynamoDB table.
- [`ElasticsearchDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ElasticsearchDataSource.html) Construct An Appsync datasource backed by Elasticsearch.
- [`EventBridgeDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.EventBridgeDataSource.html) Construct An AppSync datasource backed by EventBridge.
- [`HttpDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.HttpDataSource.html) Construct An AppSync datasource backed by a http endpoint.
- [`LambdaDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.LambdaDataSource.html) Construct An AppSync datasource backed by a Lambda function.
- [`NoneDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.NoneDataSource.html) Construct An AppSync dummy datasource.
- [`OpenSearchDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.OpenSearchDataSource.html) Construct An Appsync datasource backed by OpenSearch.
- [`RdsDataSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.RdsDataSource.html) Construct An AppSync datasource backed by RDS.
- [`Resolver`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.Resolver.html) Construct An AppSync resolver.

### Classes

- [`AppSyncEventResource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AppSyncEventResource.html) Class A class used to generate resource arns for AppSync Event APIs.
- [`AssetCode`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AssetCode.html) Class Represents a local file with source code used for an AppSync Function or Resolver.
- [`Assign`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.Assign.html) Class Utility class representing the assigment of a value to an attribute.
- [`AttributeValues`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AttributeValues.html) Class Specifies the attribute value assignments.
- [`AttributeValuesStep`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.AttributeValuesStep.html) Class Utility class to allow assigning a value to an attribute.
- [`Code`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.Code.html) Class Represents source code for an AppSync Function or Resolver.
- [`Definition`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.Definition.html) Class AppSync definition.
- [`FunctionRuntime`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.FunctionRuntime.html) Class Utility class for specifying specific appsync runtime versions.
- [`IamResource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.IamResource.html) Class A class used to generate resource arns for AppSync.
- [`InlineCode`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.InlineCode.html) Class AppSync function code from an inline string.
- [`KeyCondition`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.KeyCondition.html) Class Factory class for DynamoDB key conditions.
- [`MappingTemplate`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.MappingTemplate.html) Class MappingTemplates for AppSync resolvers.
- [`PartitionKey`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.PartitionKey.html) Class Specifies the assignment to the partition key.
- [`PartitionKeyStep`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.PartitionKeyStep.html) Class Utility class to allow assigning a value or an auto-generated id to a partition key.
- [`PrimaryKey`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.PrimaryKey.html) Class Specifies the assignment to the primary key.
- [`SchemaFile`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.SchemaFile.html) Class The Schema for a GraphQL Api.
- [`SortKeyStep`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.SortKeyStep.html) Class Utility class to allow assigning a value or an auto-generated id to a sort key.
- [`Values`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.Values.html) Class Factory class for attribute value assignments.

### Interfaces

- [`IApi`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.IApi.html) Interface Interface for an API.
- [`IAppSyncAuthConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.IAppSyncAuthConfig.html) Interface Exposes methods for defining authorization config for AppSync APIs.
- [`IAppsyncFunction`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.IAppsyncFunction.html) Interface Interface for AppSync Functions.
- [`IChannelNamespace`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.IChannelNamespace.html) Interface An AppSync channel namespace.
- [`IEventApi`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.IEventApi.html) Interface Interface for Event API.
- [`IGraphqlApi`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.IGraphqlApi.html) Interface Interface for GraphQL.
- [`ISchema`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ISchema.html) Interface Interface for implementing your own schema.
- [`ISchemaConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ISchemaConfig.html) Interface Configuration for bound graphql schema.
- [`ISourceApiAssociation`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ISourceApiAssociation.html) Interface Interface for AppSync Source Api Association.
