Package software.amazon.awscdk.services.appsync


package software.amazon.awscdk.services.appsync

AWS AppSync Construct Library

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

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

Example

DynamoDB

Example of a GraphQL API with AWS_IAM authorization resolving into a DynamoDb backend data source.

GraphQL schema file schema.graphql:

 type demo {
   id: String!
   version: String!
 }
 type Query {
   getDemos: [ demo! ]
 }
 input DemoInput {
   version: String!
 }
 type Mutation {
   addDemo(input: DemoInput!): demo
 }
 

CDK stack file app-stack.ts:

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

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.

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

HTTP Endpoints

GraphQL schema file schema.graphql:

 type job {
   id: String!
   version: String!
 }
 
 input DemoInput {
   version: String!
 }
 
 type Mutation {
   callStepFunction(input: DemoInput!): job
 }
 

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:

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

EventBridge

Integrating AppSync with EventBridge enables developers to use EventBridge rules to route commands for GraphQL mutations that need to perform any one of a variety of asynchronous tasks. More broadly, it enables teams to expose an event bus as a part of a GraphQL schema.

GraphQL schema file schema.graphql:

 schema {
     query: Query
     mutation: Mutation
 }
 
 type Query {
     event(id:ID!): Event
 }
 
 type Mutation {
     emitEvent(id: ID!, name: String): PutEventsResult!
 }
 
 type Event {
     id: ID!
     name: String!
 }
 
 type Entry {
     ErrorCode: String
     ErrorMessage: String
     EventId: String
 }
 
 type PutEventsResult {
     Entries: [Entry!]
     FailedEntry: Int
 }
 

GraphQL request mapping template request.vtl:

 {
     "version" : "2018-05-29",
     "operation": "PutEvents",
     "events" : [
         {
             "source": "integ.appsync.eventbridge",
             "detailType": "Mutation.emitEvent",
             "detail": $util.toJson($context.arguments)
         }
     ]
 }
 

GraphQL response mapping template response.vtl:

 $util.toJson($ctx.result)'
 

This response mapping template simply converts the EventBridge PutEvents result to JSON. For details about the response see the documentation. Additional logic can be added to the response template to map the response type, or to error in the event of failed events. More information can be found here.

CDK stack file app-stack.ts:

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

Amazon OpenSearch Service

AppSync has builtin support for Amazon OpenSearch Service (successor to Amazon Elasticsearch Service) from domains that are provisioned through your AWS account. You can use AppSync resolvers to perform GraphQL operations such as queries, mutations, and subscriptions.

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

Merged APIs

AppSync supports Merged APIs which can be used to merge multiple source APIs into a single API.

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

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.

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

Merge Source API Update Within CDK Deployment

The SourceApiAssociationMergeOperation construct available in the awscdk-appsync-utils package provides the ability to merge a source API to a Merged API via a custom resource. If the merge operation fails with a conflict, the stack update will fail and rollback the changes to the source API in the stack in order to prevent merge conflicts and ensure the source API changes are always propagated to the Merged API.

Custom Domain Names

For many use cases you may want to associate a custom domain name with your GraphQL API. This can be done during the API creation.

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

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.

To obtain the GraphQL API's log group as a logs.ILogGroup use the logGroup property of the GraphqlApi construct.

 import software.amazon.awscdk.services.logs.*;
 
 
 LogConfig logConfig = LogConfig.builder()
         .retention(RetentionDays.ONE_WEEK)
         .build();
 
 GraphqlApi.Builder.create(this, "api")
         .authorizationConfig(AuthorizationConfig.builder().build())
         .name("myApi")
         .definition(Definition.fromFile(join(__dirname, "myApi.graphql")))
         .logConfig(logConfig)
         .build();
 

Schema

You can define a schema using from a local file using Definition.fromFile

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

ISchema

Alternative schema sources can be defined by implementing the ISchema interface. An example of this is the CodeFirstSchema class provided in awscdk-appsync-utils

Imports

Any GraphQL Api that has been created outside the stack can be imported from another stack into your CDK app. Utilizing the fromXxx function, you have the ability to add data sources and resolvers through a IGraphqlApi interface.

 GraphqlApi api;
 Table table;
 
 IGraphqlApi importedApi = GraphqlApi.fromGraphqlApiAttributes(this, "IApi", GraphqlApiAttributes.builder()
         .graphqlApiId(api.getApiId())
         .graphqlApiArn(api.getArn())
         .build());
 importedApi.addDynamoDbDataSource("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:

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

See documentation for more details about Private APIs

Authorization

There are multiple authorization types available for GraphQL API to cater to different access use cases. They are:

  • API Keys (AuthorizationType.API_KEY)
  • Amazon Cognito User Pools (AuthorizationType.USER_POOL)
  • OpenID Connect (AuthorizationType.OPENID_CONNECT)
  • AWS Identity and Access Management (AuthorizationType.AWS_IAM)
  • AWS Lambda (AuthorizationType.AWS_LAMBDA)

These types can be used simultaneously in a single API, allowing different types of clients to access data. When you specify an authorization type, you can also specify the corresponding authorization mode to finish defining your authorization. For example, this is a GraphQL API with AWS Lambda Authorization.

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

Permissions

When using AWS_IAM as the authorization type for GraphQL API, an IAM Role with correct permissions must be used for access to API.

When configuring permissions, you can specify specific resources to only be accessible by IAM authorization. For example, if you want to only allow mutability for IAM authorized access you would configure the following.

In schema.graphql:

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

In IAM:

 {
   "Version": "2012-10-17",
   "Statement": [
     {
       "Effect": "Allow",
       "Action": [
         "appsync:GraphQL"
       ],
       "Resource": [
         "arn:aws:appsync:REGION:ACCOUNT_ID:apis/GRAPHQL_ID/types/Mutation/fields/updateExample"
       ]
     }
   ]
 }
 

See documentation for more details.

To make this easier, CDK provides grant API.

Use the grant function for more granular authorization.

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

IamResource

In order to use the grant functions, you need to use the class IamResource.

  • IamResource.custom(...arns) permits custom ARNs and requires an argument.
  • IamResouce.ofType(type, ...fields) permits ARNs for types and their fields.
  • IamResource.all() permits ALL resources.

Generic Permissions

Alternatively, you can use more generic grant functions to accomplish the same usage.

These include:

  • grantMutation (use to grant access to Mutation fields)
  • grantQuery (use to grant access to Query fields)
  • grantSubscription (use to grant access to Subscription fields)

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

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.

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

AppSync Functions are used in tandem with pipeline resolvers to compose multiple operations.

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

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.

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

Learn more about Pipeline Resolvers and AppSync Functions here.

Introspection

By default, AppSync allows you to use introspection queries.

For customers that want to limit access to be introspection queries, the introspectionConfig property can be set to IntrospectionConfig.DISABLED at creation time. If introspectionConfig is not set, the service will default to ENABLED.

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