164 types
The aws-cdk-lib/aws-appsync package contains constructs for building flexible
APIs that use GraphQL and Events.
require 'aws-cdk-lib'
Example of a GraphQL API with AWS_IAM authorization resolving into a DynamoDb
backend data source.
GraphQL schema file schema.graphql:
type demo {
id: String!
version: String!
}
type Query {
getDemos: [ demo! ]
getDemosConsistent: [demo!]
}
input DemoInput {
version: String!
}
type Mutation {
addDemo(input: DemoInput!): demo
}
CDK stack file app-stack.ts:
api = AWSCDK::AppSync::GraphqlAPI.new(self, "Api", {
name: "demo",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "schema.graphql")),
authorization_config: {
default_authorization: {
authorization_type: AWSCDK::AppSync::AuthorizationType::IAM,
},
},
xray_enabled: true,
})
demo_table = AWSCDK::DynamoDB::Table.new(self, "DemoTable", {
partition_key: {
name: "id",
type: AWSCDK::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: AWSCDK::AppSync::MappingTemplate.dynamo_db_scan_table,
response_mapping_template: AWSCDK::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: AWSCDK::AppSync::MappingTemplate.dynamo_db_put_item(AWSCDK::AppSync::PrimaryKey.partition("id").auto, AWSCDK::AppSync::Values.projecting("input")),
response_mapping_template: AWSCDK::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: AWSCDK::AppSync::MappingTemplate.dynamo_db_scan_table(true),
response_mapping_template: AWSCDK::AppSync::MappingTemplate.dynamo_db_result_list,
})
AppSync provides a data source for executing SQL commands against Amazon Aurora Serverless clusters. You can use AppSync resolvers to execute SQL statements against the Data API with GraphQL queries, mutations, and subscriptions.
# Build a data source for AppSync to access the database.
api = nil # AWSCDK::AppSync::GraphqlAPI
# Create username and password secret for DB Cluster
secret = AWSCDK::RDS::DatabaseSecret.new(self, "AuroraSecret", {
username: "clusteradmin",
})
# The VPC to place the cluster in
vpc = AWSCDK::EC2::VPC.new(self, "AuroraVpc")
# Create the serverless cluster, provide all values needed to customise the database.
cluster = AWSCDK::RDS::ServerlessCluster.new(self, "AuroraCluster", {
engine: AWSCDK::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: AWSCDK::AppSync::MappingTemplate.from_string(<<-'HERE'
{
"version": "2018-05-29",
"statements": [
"SELECT * FROM demos"
]
}
HERE),
response_mapping_template: AWSCDK::AppSync::MappingTemplate.from_string(<<-'HERE'
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
HERE),
})
# Set up a resolver for an RDS mutation.
rds_ds.create_resolver("MutationAddDemoRdsResolver", {
type_name: "Mutation",
field_name: "addDemoRds",
request_mapping_template: AWSCDK::AppSync::MappingTemplate.from_string(<<-'HERE'
{
"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)
}
}
HERE),
response_mapping_template: AWSCDK::AppSync::MappingTemplate.from_string(<<-'HERE'
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
HERE),
})
# Build a data source for AppSync to access the database.
api = nil # AWSCDK::AppSync::GraphqlAPI
# Create username and password secret for DB Cluster
secret = AWSCDK::RDS::DatabaseSecret.new(self, "AuroraSecret", {
username: "clusteradmin",
})
# The VPC to place the cluster in
vpc = AWSCDK::EC2::VPC.new(self, "AuroraVpc")
# Create the serverless cluster, provide all values needed to customise the database.
cluster = AWSCDK::RDS::DatabaseCluster.new(self, "AuroraClusterV2", {
engine: AWSCDK::RDS::DatabaseClusterEngine.aurora_postgres({version: AWSCDK::RDS::AuroraPostgresEngineVersion.VER_15_5}),
credentials: {username: "clusteradmin"},
cluster_identifier: "db-endpoint-test",
writer: AWSCDK::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: AWSCDK::AppSync::MappingTemplate.from_string(<<-'HERE'
{
"version": "2018-05-29",
"statements": [
"SELECT * FROM demos"
]
}
HERE),
response_mapping_template: AWSCDK::AppSync::MappingTemplate.from_string(<<-'HERE'
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
HERE),
})
# Set up a resolver for an RDS mutation.
rds_ds.create_resolver("MutationAddDemoRdsResolver", {
type_name: "Mutation",
field_name: "addDemoRds",
request_mapping_template: AWSCDK::AppSync::MappingTemplate.from_string(<<-'HERE'
{
"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)
}
}
HERE),
response_mapping_template: AWSCDK::AppSync::MappingTemplate.from_string(<<-'HERE'
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
HERE),
})
GraphQL schema file schema.graphql:
type job {
id: String!
version: String!
}
input DemoInput {
version: String!
}
type Mutation {
callStepFunction(input: DemoInput!): job
}
type Query {
_placeholder: String
}
GraphQL request mapping template request.vtl:
{
"version": "2018-05-29",
"method": "POST",
"resourcePath": "/",
"params": {
"headers": {
"content-type": "application/x-amz-json-1.0",
"x-amz-target":"AWSStepFunctions.StartExecution"
},
"body": {
"stateMachineArn": "<your step functions arn>",
"input": "{ \"id\": \"$context.arguments.id\" }"
}
}
}
GraphQL response mapping template response.vtl:
{
"id": "${context.result.id}"
}
CDK stack file app-stack.ts:
api = AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
name: "api",
definition: AWSCDK::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: {
signing_region: "us-east-1",
signing_service_name: "states",
},
})
http_ds.create_resolver("MutationCallStepFunctionResolver", {
type_name: "Mutation",
field_name: "callStepFunction",
request_mapping_template: AWSCDK::AppSync::MappingTemplate.from_file("request.vtl"),
response_mapping_template: AWSCDK::AppSync::MappingTemplate.from_file("response.vtl"),
})
Integrating AppSync with EventBridge enables developers to use EventBridge rules to route commands for GraphQL mutations that need to perform any one of a variety of asynchronous tasks. More broadly, it enables teams to expose an event bus as a part of a GraphQL schema.
GraphQL schema file schema.graphql:
schema {
query: Query
mutation: Mutation
}
type Query {
event(id:ID!): Event
}
type Mutation {
emitEvent(id: ID!, name: String): PutEventsResult!
}
type Event {
id: ID!
name: String!
}
type Entry {
ErrorCode: String
ErrorMessage: String
EventId: String
}
type PutEventsResult {
Entries: [Entry!]
FailedEntry: Int
}
GraphQL request mapping template request.vtl:
{
"version" : "2018-05-29",
"operation": "PutEvents",
"events" : [
{
"source": "integ.appsync.eventbridge",
"detailType": "Mutation.emitEvent",
"detail": $util.toJson($context.arguments)
}
]
}
GraphQL response mapping template response.vtl:
$util.toJson($ctx.result)'
This response mapping template simply converts the EventBridge PutEvents result to JSON. For details about the response see the documentation. Additional logic can be added to the response template to map the response type, or to error in the event of failed events. More information can be found here.
CDK stack file app-stack.ts:
require 'aws-cdk-lib'
api = AWSCDK::AppSync::GraphqlAPI.new(self, "EventBridgeApi", {
name: "EventBridgeApi",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "appsync.eventbridge.graphql")),
})
bus = AWSCDK::Events::EventBus.new(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: AWSCDK::AppSync::MappingTemplate.from_file("request.vtl"),
response_mapping_template: AWSCDK::AppSync::MappingTemplate.from_file("response.vtl"),
})
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.
require 'aws-cdk-lib'
api = nil # AWSCDK::AppSync::GraphqlAPI
user = AWSCDK::IAM::User.new(self, "User")
domain = AWSCDK::OpenSearchService::Domain.new(self, "Domain", {
version: AWSCDK::OpenSearchService::EngineVersion.OPENSEARCH_2_3,
removal_policy: AWSCDK::RemovalPolicy::DESTROY,
fine_grained_access_control: {master_user_arn: user.user_arn},
encryption_at_rest: {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: AWSCDK::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: AWSCDK::AppSync::MappingTemplate.from_string(<<-'HERE'
[
#foreach($entry in $context.result.hits.hits)
#if( $velocityCount > 1 ) , #end
$utils.toJson($entry.get("_source"))
#end
]
HERE),
})
AppSync supports Merged APIs which can be used to merge multiple source APIs into a single API.
require 'aws-cdk-lib'
# first source API
first_api = AWSCDK::AppSync::GraphqlAPI.new(self, "FirstSourceAPI", {
name: "FirstSourceAPI",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "appsync.merged-api-1.graphql")),
})
# second source API
second_api = AWSCDK::AppSync::GraphqlAPI.new(self, "SecondSourceAPI", {
name: "SecondSourceAPI",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "appsync.merged-api-2.graphql")),
})
# Merged API
merged_api = AWSCDK::AppSync::GraphqlAPI.new(self, "MergedAPI", {
name: "MergedAPI",
definition: AWSCDK::AppSync::Definition.from_source_apis({
source_apis: [
{
source_api: first_api,
merge_type: AWSCDK::AppSync::MergeType::MANUAL_MERGE,
},
{
source_api: second_api,
merge_type: AWSCDK::AppSync::MergeType::AUTO_MERGE,
},
],
}),
})
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.
source_api = AWSCDK::AppSync::GraphqlAPI.new(self, "FirstSourceAPI", {
name: "FirstSourceAPI",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "appsync.merged-api-1.graphql")),
})
imported_merged_api = AWSCDK::AppSync::GraphqlAPI.from_graphql_api_attributes(self, "ImportedMergedApi", {
graphql_api_id: "MyApiId",
graphql_api_arn: "MyApiArn",
})
imported_execution_role = AWSCDK::IAM::Role.from_role_arn(self, "ExecutionRole", "arn:aws:iam::ACCOUNT:role/MyExistingRole")
AWSCDK::AppSync::SourceAPIAssociation.new(self, "SourceApiAssociation2", {
source_api: source_api,
merged_api: imported_merged_api,
merge_type: AWSCDK::AppSync::MergeType::MANUAL_MERGE,
merged_api_execution_role: imported_execution_role,
})
The SourceApiAssociationMergeOperation construct available in the awscdk-appsync-utils package provides the ability to merge a source API to a Merged API via a custom resource. If the merge operation fails with a conflict, the stack update will fail and rollback the changes to the source API in the stack in order to prevent merge conflicts and ensure the source API changes are always propagated to the Merged API.
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.
require 'aws-cdk-lib'
# hosted zone and route53 features
hosted_zone_id = nil
zone_name = "example.com"
my_domain_name = "api.example.com"
certificate = AWSCDK::CertificateManager::Certificate.new(self, "cert", {domain_name: my_domain_name})
schema = AWSCDK::AppSync::SchemaFile.new({file_path: "mySchemaFile"})
api = AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
name: "myApi",
definition: AWSCDK::AppSync::Definition.from_schema(schema),
domain_name: {
certificate: certificate,
domain_name: my_domain_name,
},
})
# hosted zone for adding appsync domain
zone = AWSCDK::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
AWSCDK::Route53::CnameRecord.new(self, "CnameApiRecord", {
record_name: "api",
zone: zone,
domain_name: api.app_sync_domain_name,
})
AppSync automatically create a log group with the name /aws/appsync/apis/<graphql_api_id> upon deployment with
log data set to never expire. If you want to set a different expiration period, use the logConfig.retention property.
Also you can choose the log level by setting the logConfig.fieldLogLevel property.
For more information, see CloudWatch logs.
To obtain the GraphQL API's log group as a logs.ILogGroup use the log_group property of the
GraphqlApi construct.
require 'aws-cdk-lib'
AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
authorization_config: {},
name: "myApi",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "myApi.graphql")),
log_config: {
field_log_level: AWSCDK::AppSync::FieldLogLevel::INFO,
retention: AWSCDK::Logs::RetentionDays::ONE_WEEK,
},
})
You can define a schema using from a local file using Definition.fromFile
api = AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
name: "myApi",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "schema.graphl")),
})
Alternative schema sources can be defined by implementing the ISchema
interface. An example of this is the CodeFirstSchema class provided in
awscdk-appsync-utils
Any GraphQL Api that has been created outside the stack can be imported from
another stack into your CDK app. Utilizing the from_xxx function, you have
the ability to add data sources and resolvers through a IGraphqlApi interface.
api = nil # AWSCDK::AppSync::GraphqlAPI
table = nil # AWSCDK::DynamoDB::Table
imported_api = AWSCDK::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)
If you don't specify graphql_arn in from_xxx_attributes, CDK will autogenerate
the expected arn for the imported api, given the api_id. For creating data
sources and resolvers, an api_id is sufficient.
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:
api = AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
name: "MyPrivateAPI",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
visibility: AWSCDK::AppSync::Visibility::PRIVATE,
})
See documentation for more details about Private APIs
There are multiple authorization types available for GraphQL API to cater to different access use cases. They are:
AuthorizationType.API_KEY)AuthorizationType.USER_POOL)AuthorizationType.OPENID_CONNECT)AuthorizationType.AWS_IAM)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.
require 'aws-cdk-lib'
auth_function = nil # AWSCDK::Lambda::Function
AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
name: "api",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "appsync.test.graphql")),
authorization_config: {
default_authorization: {
authorization_type: AWSCDK::AppSync::AuthorizationType::LAMBDA,
lambda_authorizer_config: {
handler: auth_function,
},
},
},
})
When using AWS_IAM as the authorization type for GraphQL API, an IAM Role
with correct permissions must be used for access to API.
When configuring permissions, you can specify specific resources to only be
accessible by IAM authorization. For example, if you want to only allow mutability
for IAM authorized access you would configure the following.
In schema.graphql:
type Mutation {
updateExample(...): ...
@aws_iam
}
In IAM:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"appsync:GraphQL"
],
"Resource": [
"arn:aws:appsync:REGION:ACCOUNT_ID:apis/GRAPHQL_ID/types/Mutation/fields/updateExample"
]
}
]
}
See documentation for more details.
To make this easier, CDK provides grant API.
Use the grant function for more granular authorization.
api = nil # AWSCDK::AppSync::IGraphqlAPI
role = AWSCDK::IAM::Role.new(self, "Role", {
assumed_by: AWSCDK::IAM::ServicePrincipal.new("lambda.amazonaws.com"),
})
api.grant(role, AWSCDK::AppSync::IAMResource.custom("types/Mutation/fields/updateExample"), "appsync:GraphQL")
In order to use the grant functions, you need to use the class IamResource.
IamResource.custom(...arns) permits custom ARNs and requires an argument.IamResouce.ofType(type, ...fields) permits ARNs for types and their fields.IamResource.all() permits ALL resources.Alternatively, you can use more generic grant functions to accomplish the same usage.
These include:
api = nil # AWSCDK::AppSync::IGraphqlAPI
role = nil # AWSCDK::IAM::Role
# For generic types
api.grant_mutation(role, "updateExample")
# For custom types and granular design
api.grant(role, AWSCDK::AppSync::IAMResource.of_type("Mutation", "updateExample"), "appsync:GraphQL")
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.
api = nil # AWSCDK::AppSync::GraphqlAPI
appsync_function = AWSCDK::AppSync::AppsyncFunction.new(self, "function", {
name: "appsync_function",
api: api,
data_source: api.add_none_data_source("none"),
request_mapping_template: AWSCDK::AppSync::MappingTemplate.from_file("request.vtl"),
response_mapping_template: AWSCDK::AppSync::MappingTemplate.from_file("response.vtl"),
})
When using the LambdaDataSource, you can control the maximum number of resolver request
inputs that will be sent to a single AWS Lambda function in a BatchInvoke operation
by setting the max_batch_size property.
api = nil # AWSCDK::AppSync::GraphqlAPI
lambda_data_source = nil # AWSCDK::AppSync::LambdaDataSource
appsync_function = AWSCDK::AppSync::AppsyncFunction.new(self, "function", {
name: "appsync_function",
api: api,
data_source: lambda_data_source,
max_batch_size: 10,
})
AppSync Functions are used in tandem with pipeline resolvers to compose multiple operations.
api = nil # AWSCDK::AppSync::GraphqlAPI
appsync_function = nil # AWSCDK::AppSync::AppsyncFunction
pipeline_resolver = AWSCDK::AppSync::Resolver.new(self, "pipeline", {
api: api,
data_source: api.add_none_data_source("none"),
type_name: "typeName",
field_name: "fieldName",
request_mapping_template: AWSCDK::AppSync::MappingTemplate.from_file("beforeRequest.vtl"),
pipeline_config: [appsync_function],
response_mapping_template: AWSCDK::AppSync::MappingTemplate.from_file("afterResponse.vtl"),
})
JS Functions and resolvers are also supported. You can use a .js file within your CDK project, or specify your function code inline.
api = nil # AWSCDK::AppSync::GraphqlAPI
my_js_function = AWSCDK::AppSync::AppsyncFunction.new(self, "function", {
name: "my_js_function",
api: api,
data_source: api.add_none_data_source("none"),
code: AWSCDK::AppSync::Code.from_asset("directory/function_code.js"),
runtime: AWSCDK::AppSync::FunctionRuntime.JS_1_0_0,
})
AWSCDK::AppSync::Resolver.new(self, "PipelineResolver", {
api: api,
type_name: "typeName",
field_name: "fieldName",
code: AWSCDK::AppSync::Code.from_inline(<<-'HERE'
// The before step
export function request(...args) {
console.log(args);
return {}
}
// The after step
export function response(ctx) {
return ctx.prev.result
}
HERE),
runtime: AWSCDK::AppSync::FunctionRuntime.JS_1_0_0,
pipeline_config: [my_js_function],
})
Learn more about Pipeline Resolvers and AppSync Functions here.
By default, AppSync allows you to use introspection queries.
For customers that want to limit access to be introspection queries, the introspection_config property can be set to IntrospectionConfig.DISABLED at creation time.
If introspection_config is not set, the service will default to ENABLED.
api = AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
name: "DisableIntrospectionApi",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
introspection_config: AWSCDK::AppSync::IntrospectionConfig::DISABLED,
})
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.
api = AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
name: "LimitQueryDepths",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
query_depth_limit: 2,
})
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.
api = AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
name: "LimitResolverCount",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
resolver_count_limit: 2,
})
To use environment variables in resolvers, you can use the environment_variables property and
the add_environment_variable method.
api = AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
name: "api",
definition: AWSCDK::AppSync::Definition.from_file(path.join(__dirname, "appsync.schema.graphql")),
environment_variables: {
EnvKey1: "non-empty-1",
},
})
api.add_environment_variable("EnvKey2", "non-empty-2")
Configuring the target relies on the graph_ql_endpoint_arn 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.
require 'aws-cdk-lib'
rule = nil # AWSCDK::Events::Rule
api = nil # AWSCDK::AppSync::GraphqlAPI
rule.add_target(AWSCDK::EventsTargets::AppSync.new(api, {
graph_ql_operation: "mutation Publish($message: String!){ publish(message: $message) { message } }",
variables: AWSCDK::Events::RuleTargetInput.from_object({
message: "hello world",
}),
}))
You can set the owner contact information for an API resource. This field accepts any string input with a length of 0 - 256 characters.
api = AWSCDK::AppSync::GraphqlAPI.new(self, "OwnerContact", {
name: "OwnerContact",
definition: AWSCDK::AppSync::Definition.from_schema(AWSCDK::AppSync::SchemaFile.from_asset(path.join(__dirname, "appsync.test.graphql"))),
owner_contact: "test-owner-contact",
})
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.
schema = AWSCDK::AppSync::SchemaFile.new({file_path: "mySchemaFile"})
AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
name: "myApi",
definition: AWSCDK::AppSync::Definition.from_schema(schema),
enhanced_metrics_config: {
data_source_level_metrics_behavior: AWSCDK::AppSync::DataSourceLevelMetricsBehavior::FULL_REQUEST_DATA_SOURCE_METRICS,
operation_level_metrics_config: AWSCDK::AppSync::OperationLevelMetricsConfig::ENABLED,
resolver_level_metrics_behavior: AWSCDK::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.
schema = AWSCDK::AppSync::SchemaFile.new({file_path: "mySchemaFile"})
api = AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
name: "myApi",
definition: AWSCDK::AppSync::Definition.from_schema(schema),
enhanced_metrics_config: {
data_source_level_metrics_behavior: AWSCDK::AppSync::DataSourceLevelMetricsBehavior::PER_DATA_SOURCE_METRICS,
operation_level_metrics_config: AWSCDK::AppSync::OperationLevelMetricsConfig::ENABLED,
resolver_level_metrics_behavior: AWSCDK::AppSync::ResolverLevelMetricsBehavior::PER_RESOLVER_METRICS,
},
})
none_ds = api.add_none_data_source("none", {
metrics_config: AWSCDK::AppSync::DataSourceMetricsConfig::ENABLED,
})
none_ds.create_resolver("noneResolver", {
type_name: "Mutation",
field_name: "addDemoMetricsConfig",
metrics_config: AWSCDK::AppSync::ResolverMetricsConfig::ENABLED,
})
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.
api_key_provider = {
authorization_type: AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
}
api = AWSCDK::AppSync::EventAPI.new(self, "api", {
api_name: "Api",
owner_contact: "OwnerContact",
authorization_config: {
auth_providers: [
api_key_provider,
],
connection_auth_mode_types: [
AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
],
default_publish_auth_mode_types: [
AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
],
default_subscribe_auth_mode_types: [
AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
],
},
})
api.add_channel_namespace("default")
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:
AppSyncAuthorizationType.API_KEY)AppSyncAuthorizationType.USER_POOL)AppSyncAuthorizationType.OIDC)AppSyncAuthorizationType.IAM)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.
require 'aws-cdk-lib'
handler = nil # AWSCDK::Lambda::Function
iam_provider = {
authorization_type: AWSCDK::AppSync::AppSyncAuthorizationType::IAM,
}
api_key_provider = {
authorization_type: AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
}
lambda_provider = {
authorization_type: AWSCDK::AppSync::AppSyncAuthorizationType::LAMBDA,
lambda_authorizer_config: {
handler: handler,
results_cache_ttl: AWSCDK::Duration.minutes(6),
validation_regex: "test",
},
}
api = AWSCDK::AppSync::EventAPI.new(self, "api", {
api_name: "api",
authorization_config: {
# set auth providers
auth_providers: [
iam_provider,
api_key_provider,
lambda_provider,
],
connection_auth_mode_types: [
AWSCDK::AppSync::AppSyncAuthorizationType::IAM,
],
default_publish_auth_mode_types: [
AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
],
default_subscribe_auth_mode_types: [
AWSCDK::AppSync::AppSyncAuthorizationType::LAMBDA,
],
},
})
api.add_channel_namespace("default")
If you don't specify any overrides for the connection_auth_mode_types, default_publish_auth_mode_types, and default_subscribe_auth_mode_types parameters then all auth_providers defined are included as default authorization mode types for connection, publish, and subscribe.
require 'aws-cdk-lib'
handler = nil # AWSCDK::Lambda::Function
iam_provider = {
authorization_type: AWSCDK::AppSync::AppSyncAuthorizationType::IAM,
}
api_key_provider = {
authorization_type: AWSCDK::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 = AWSCDK::AppSync::EventAPI.new(self, "api", {
api_name: "api",
authorization_config: {
# set auth providers
auth_providers: [
iam_provider,
api_key_provider,
],
},
})
api.add_channel_namespace("default")
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 on_publish and on_subscribe operations.
Below are examples for how you add the various data sources to you Event API.
api = AWSCDK::AppSync::EventAPI.new(self, "EventApiDynamoDB", {
api_name: "DynamoDBEventApi",
})
table = AWSCDK::DynamoDB::Table.new(self, "table", {
table_name: "event-messages",
partition_key: {
name: "id",
type: AWSCDK::DynamoDB::AttributeType::STRING,
},
})
data_source = api.add_dynamo_db_data_source("ddbsource", table)
require 'aws-cdk-lib'
vpc = nil # AWSCDK::EC2::VPC
database_name = "mydb"
cluster = AWSCDK::RDS::DatabaseCluster.new(self, "Cluster", {
engine: AWSCDK::RDS::DatabaseClusterEngine.aurora_postgres({version: AWSCDK::RDS::AuroraPostgresEngineVersion.VER_16_6}),
writer: AWSCDK::RDS::ClusterInstance.serverless_v2("writer"),
vpc: vpc,
credentials: {username: "clusteradmin"},
default_database_name: database_name,
enable_data_api: true,
})
secret = AWSCDK::SecretsManager::Secret.from_secret_name_v2(self, "Secret", "db-secretName")
api = AWSCDK::AppSync::EventAPI.new(self, "EventApiRds", {
api_name: "RdsEventApi",
})
data_source = api.add_rds_data_source("rdsds", cluster, secret, database_name)
require 'aws-cdk-lib'
api = AWSCDK::AppSync::EventAPI.new(self, "EventApiEventBridge", {
api_name: "EventBridgeEventApi",
})
event_bus = AWSCDK::Events::EventBus.new(self, "test-bus")
data_source = api.add_event_bridge_data_source("eventbridgeds", event_bus)
require 'aws-cdk-lib'
lambda_ds = nil # AWSCDK::Lambda::Function
api = AWSCDK::AppSync::EventAPI.new(self, "EventApiLambda", {
api_name: "LambdaEventApi",
})
data_source = api.add_lambda_data_source("lambdads", lambda_ds)
require 'aws-cdk-lib'
domain = AWSCDK::OpenSearchService::Domain.new(self, "Domain", {
version: AWSCDK::OpenSearchService::EngineVersion.OPENSEARCH_2_17,
encryption_at_rest: {
enabled: true,
},
node_to_node_encryption: true,
enforce_https: true,
capacity: {
multi_az_with_standby_enabled: false,
},
ebs: {
enabled: true,
volume_size: 10,
},
})
api = AWSCDK::AppSync::EventAPI.new(self, "EventApiOpenSearch", {
api_name: "OpenSearchEventApi",
})
data_source = api.add_open_search_data_source("opensearchds", domain)
require 'aws-cdk-lib'
api = AWSCDK::AppSync::EventAPI.new(self, "EventApiHttp", {
api_name: "HttpEventApi",
})
random_api = AWSCDK::APIGateway::RestAPI.new(self, "RandomApi")
random_route = random_api.root.add_resource("random")
random_route.add_method("GET", AWSCDK::APIGateway::MockIntegration.new({
integration_responses: [
{
status_code: "200",
response_templates: {
"application/json" => "my-random-value",
},
},
],
passthrough_behavior: AWSCDK::APIGateway::PassthroughBehavior::NEVER,
request_templates: {
"application/json" => "{ \"statusCode\": 200 }",
},
}), {
method_responses: [{status_code: "200"}],
})
data_source = api.add_http_data_source("httpsource", "https://#{random_api.rest_api_id}.execute-api.#{@region}.amazonaws.com")
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 domain_name. Also you can get custom HTTP/Realtime endpoint by custom_http_endpoint, custom_realtime_endpoint.
For more information, see Configuring custom domain names for Event APIs.
require 'aws-cdk-lib'
my_domain_name = "api.example.com"
certificate = AWSCDK::CertificateManager::Certificate.new(self, "cert", {domain_name: my_domain_name})
api_key_provider = {
authorization_type: AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
}
api = AWSCDK::AppSync::EventAPI.new(self, "api", {
api_name: "Api",
owner_contact: "OwnerContact",
authorization_config: {
auth_providers: [
api_key_provider,
],
connection_auth_mode_types: [
AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
],
default_publish_auth_mode_types: [
AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
],
default_subscribe_auth_mode_types: [
AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
],
},
# Custom Domain Settings
domain_name: {
certificate: certificate,
domain_name: my_domain_name,
},
})
api.add_channel_namespace("default")
# You can get custom HTTP/Realtime endpoint
AWSCDK::CfnOutput.new(self, "AWS AppSync Events HTTP endpoint", {value: api.custom_http_endpoint})
AWSCDK::CfnOutput.new(self, "AWS AppSync Events Realtime endpoint", {value: api.custom_realtime_endpoint})
AppSync automatically create a log group with the name /aws/appsync/apis/<api_id> upon deployment with log data set to never expire.
If you want to set a different expiration period, use the logConfig.retention property.
Also you can choose the log level by setting the logConfig.fieldLogLevel property.
For more information, see Configuring CloudWatch Logs on Event APIs.
To obtain the Event API's log group as a logs.ILogGroup use the log_group property of the
Api construct.
require 'aws-cdk-lib'
api_key_provider = {
authorization_type: AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
}
api = AWSCDK::AppSync::EventAPI.new(self, "api", {
api_name: "Api",
owner_contact: "OwnerContact",
authorization_config: {
auth_providers: [
api_key_provider,
],
connection_auth_mode_types: [
AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
],
default_publish_auth_mode_types: [
AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
],
default_subscribe_auth_mode_types: [
AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY,
],
},
log_config: {
field_log_level: AWSCDK::AppSync::AppSyncFieldLogLevel::INFO,
retention: AWSCDK::Logs::RetentionDays::ONE_WEEK,
},
})
api.add_channel_namespace("default")
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.
api = nil # AWSCDK::AppSync::EventAPI
web_acl = nil # AWSCDK::WAFv2::CfnWebACL
# Associate waf with Event API
AWSCDK::WAFv2::CfnWebACLAssociation.new(self, "WafAssociation", {
resource_arn: api.api_arn,
web_acl_arn: web_acl.attr_arn,
})
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.
api = nil # AWSCDK::AppSync::EventAPI
# create a channel namespace
AWSCDK::AppSync::ChannelNamespace.new(self, "Namespace", {
api: api,
})
# You can also create a namespace through the addChannelNamespace method
api.add_channel_namespace("AnotherNameSpace", {})
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.
api = nil # AWSCDK::AppSync::EventAPI
AWSCDK::AppSync::ChannelNamespace.new(self, "Namespace", {
api: api,
authorization_config: {
# Override publishing authorization to API Key
publish_auth_mode_types: [AWSCDK::AppSync::AppSyncAuthorizationType::API_KEY],
# Override subscribing authorization to Lambda
subscribe_auth_mode_types: [AWSCDK::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.
api = nil # AWSCDK::AppSync::EventAPI
AWSCDK::AppSync::ChannelNamespace.new(self, "Namespace", {
api: api,
# set a handler from inline code
code: AWSCDK::AppSync::Code.from_inline("/* event handler code here.*/"),
})
AWSCDK::AppSync::ChannelNamespace.new(self, "Namespace", {
api: api,
# set a handler from an asset
code: AWSCDK::AppSync::Code.from_asset("directory/function_code.js"),
})
You can define an integration in your event handler for on_publish and/or on_subscribe 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 on_publish operations, you can persist those events to DynamoDB using a batch_put 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 on_publish 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 invoke_type 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.
api = nil # AWSCDK::AppSync::EventAPI
ddb_data_source = nil # AWSCDK::AppSync::AppSyncDynamoDBDataSource
eb_data_source = nil # AWSCDK::AppSync::AppSyncEventBridgeDataSource
# DynamoDB data source for publish handler
api.add_channel_namespace("ddb-eb-ns", {
code: AWSCDK::AppSync::Code.from_inline("/* event handler code here.*/"),
publish_handler_config: {
data_source: ddb_data_source,
},
subscribe_handler_config: {
data_source: eb_data_source,
},
})
api = nil # AWSCDK::AppSync::EventAPI
lambda_data_source = nil # AWSCDK::AppSync::AppSyncLambdaDataSource
# Lambda data source for publish handler
api.add_channel_namespace("lambda-ns", {
code: AWSCDK::AppSync::Code.from_inline("/* event handler code here.*/"),
publish_handler_config: {
data_source: lambda_data_source,
},
})
# Direct Lambda data source for publish handler
api.add_channel_namespace("lambda-direct-ns", {
publish_handler_config: {
data_source: lambda_data_source,
direct: true,
},
})
api.add_channel_namespace("lambda-direct-async-ns", {
publish_handler_config: {
data_source: lambda_data_source,
direct: true,
lambda_invoke_type: AWSCDK::AppSync::LambdaInvokeType::EVENT,
},
})