Package: aws-cdk.aws-appsync-alpha
AWS AppSync Construct Library---The APIs of higher level constructs in this module are experimental and under active development.
They are subject to non-backward compatible changes or removal in any future version. These are
not subject to theSemantic Versioningmodel and breaking changes will be
announced in the release notes. This means that while you may use them, you may need to update
your source code when upgrading to a newer version of this package.The@aws-cdk/aws-appsyncpackage contains constructs for building flexible
APIs that use GraphQL.importaws_cdk.aws_appsync_alphaasappsyncExampleDynamoDBExample of a GraphQL API withAWS_IAMauthorizationresolving into a DynamoDb
backend data source.GraphQL schema fileschema.graphql:type demo {
  id: String!
  version: String!
}
type Query {
  getDemos: [ demo! ]
}
input DemoInput {
  version: String!
}
type Mutation {
  addDemo(input: DemoInput!): demo
}CDK stack fileapp-stack.ts:api=appsync.GraphqlApi(self,"Api",name="demo",schema=appsync.SchemaFile.from_asset(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.htmldemo_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())Aurora ServerlessAppSync 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: appsync.GraphqlApi# Create username and password secret for DB Clustersecret=rds.DatabaseSecret(self,"AuroraSecret",username="clusteradmin")# The VPC to place the cluster invpc=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])"""))HTTP EndpointsGraphQL schema fileschema.graphql:type job {
  id: String!
  version: String!
}

input DemoInput {
  version: String!
}

type Mutation {
  callStepFunction(input: DemoInput!): job
}GraphQL request mapping templaterequest.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 templateresponse.vtl:{"id":"${context.result.id}"}CDK stack fileapp-stack.ts:api=appsync.GraphqlApi(self,"api",name="api",schema=appsync.SchemaFile.from_asset(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"))Amazon OpenSearch ServiceAppSync 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.importaws_cdk.aws_opensearchserviceasopensearch# api: appsync.GraphqlApiuser=iam.User(self,"User")domain=opensearch.Domain(self,"Domain",version=opensearch.EngineVersion.OPENSEARCH_1_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]"""))Custom Domain NamesFor many use cases you may want to associate a custom domain name with your
GraphQL API. This can be done during the API creation.importaws_cdk.aws_certificatemanagerasacmimportaws_cdk.aws_route53asroute53# hosted zone and route53 features# hosted_zone_id: strzone_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",schema=schema,domain_name=appsync.DomainOptions(certificate=certificate,domain_name=my_domain_name))# hosted zone for adding appsync domainzone=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.netroute53.CnameRecord(self,"CnameApiRecord",record_name="api",zone=zone,domain_name=api.app_sync_domain_name)Log GroupAppSync 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 thelogConfig.retentionproperty.To obtain the GraphQL API's log group as alogs.ILogGroupuse thelogGroupproperty of theGraphqlApiconstruct.importaws_cdk.aws_logsaslogslog_config=appsync.LogConfig(retention=logs.RetentionDays.ONE_WEEK)appsync.GraphqlApi(self,"api",authorization_config=appsync.AuthorizationConfig(),name="myApi",schema=appsync.SchemaFile.from_asset(path.join(__dirname,"myApi.graphql")),log_config=log_config)SchemaYou can define a schema using from a local file usingSchemaFile.fromAssetapi=appsync.GraphqlApi(self,"api",name="myApi",schema=appsync.SchemaFile.from_asset(path.join(__dirname,"schema.graphl")))ISchemaAlternative schema sources can be defined by implementing theISchemainterface. An example of this is theCodeFirstSchemaclass provided inawscdk-appsync-utilsImportsAny GraphQL Api that has been created outside the stack can be imported from
another stack into your CDK app. Utilizing thefromXxxfunction, you have
the ability to add data sources and resolvers through aIGraphqlApiinterface.# api: appsync.GraphqlApi# table: dynamodb.Tableimported_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)If you don't specifygraphqlArninfromXxxAttributes, CDK will autogenerate
the expectedarnfor the imported api, given theapiId. For creating data
sources and resolvers, anapiIdis sufficient.AuthorizationThere 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.importaws_cdk.aws_lambdaaslambda_# auth_function: lambda.Functionappsync.GraphqlApi(self,"api",name="api",schema=appsync.SchemaFile.from_asset(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))))PermissionsWhen usingAWS_IAMas 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 byIAMauthorization. For example, if you want to only allow mutability
forIAMauthorized access you would configure the following.Inschema.graphql:type Mutation {
  updateExample(...): ...
    @aws_iam
}InIAM:{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["appsync:GraphQL"],"Resource":["arn:aws:appsync:REGION:ACCOUNT_ID:apis/GRAPHQL_ID/types/Mutation/fields/updateExample"]}]}Seedocumentationfor more details.To make this easier, CDK providesgrantAPI.Use thegrantfunction for more granular authorization.# api: appsync.GraphqlApirole=iam.Role(self,"Role",assumed_by=iam.ServicePrincipal("lambda.amazonaws.com"))api.grant(role,appsync.IamResource.custom("types/Mutation/fields/updateExample"),"appsync:GraphQL")IamResourceIn order to use thegrantfunctions, you need to use the classIamResource.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 PermissionsAlternatively, you can use more genericgrantfunctions 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)# api: appsync.GraphqlApi# role: iam.Role# For generic typesapi.grant_mutation(role,"updateExample")# For custom types and granular designapi.grant(role,appsync.IamResource.of_type("Mutation","updateExample"),"appsync:GraphQL")Pipeline Resolvers and AppSync FunctionsAppSync 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: appsync.GraphqlApiappsync_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"))AppSync Functions are used in tandem with pipeline resolvers to compose multiple
operations.# api: appsync.GraphqlApi# appsync_function: appsync.AppsyncFunctionpipeline_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"))Learn more about Pipeline Resolvers and AppSync Functionshere.