Package: aws-cdk.aws-appsync
AWS AppSync Construct Library---AWS CDK v1 has reached End-of-Support on 2023-06-01.
This package is no longer being updated, and users should migrate to AWS CDK v2.For more information on how to migrate, see theMigrating to AWS CDK v2guide.The@aws-cdk/aws-appsyncpackage contains constructs for building flexible
APIs that use GraphQL.importaws_cdk.aws_appsyncasappsyncExampleDynamoDBExample 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.Schema.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.demo_dS.create_resolver(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(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())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(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(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.Schema.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(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_2,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(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)api=appsync.GraphqlApi(self,"api",name="myApi",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=my_domain_name)SchemaEvery GraphQL Api needs a schema to define the Api. CDK offersappsync.Schemafor static convenience methods for various types of schema declaration: code-first
or schema-first.Code-FirstWhen declaring your GraphQL Api, CDK defaults to a code-first approach if theschemaproperty is not configured.api=appsync.GraphqlApi(self,"api",name="myApi")CDK will declare aSchemaclass that will give your Api access functions to
define your schema code-first:addType,addToSchema, etc.You can also declare yourSchemaclass outside of your CDK stack, to define
your schema externally.schema=appsync.Schema()schema.add_type(appsync.ObjectType("demo",definition={"id":appsync.GraphqlType.id()}))api=appsync.GraphqlApi(self,"api",name="myApi",schema=schema)See thecode-first schemasection for more details.Schema-FirstYou can define your GraphQL Schema from a file on disk. For convenience, use
theappsync.Schema.fromAssetto specify the file representing your schema.api=appsync.GraphqlApi(self,"api",name="myApi",schema=appsync.Schema.from_asset(path.join(__dirname,"schema.graphl")))ImportsAny 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.Schema.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.Code-First SchemaCDK offers the ability to generate your schema in a code-first approach.
A code-first approach offers a developer workflow with:modularity: organizing schema type definitions into different filesreusability: simplifying down boilerplate/repetitive codeconsistency: resolvers and schema definition will always be syncedThe code-first approach allows fordynamicschema generation. You can generate your schema based on variables and templates to reduce code duplication.Code-First ExampleTo showcase the code-first approach. Let's try to model the following schema segment.interface Node {
  id: String
}

type Query {
  allFilms(after: String, first: Int, before: String, last: Int): FilmConnection
}

type FilmNode implements Node {
  filmName: String
}

type FilmConnection {
  edges: [FilmEdge]
  films: [Film]
  totalCount: Int
}

type FilmEdge {
  node: Film
  cursor: String
}Above we see a schema that allows for generating paginated responses. For example,
we can queryallFilms(first: 100)sinceFilmConnectionacts as an intermediary
for holdingFilmEdgeswe can write a resolver to return the first 100 films.In a separate file, we can declare our object types and related functions.
We will call this fileobject-types.tsand we will have created it in a way that
allows us to generate otherXxxConnectionandXxxEdgesin the future.importaws_cdk.aws_appsyncasappsyncpluralize=require("pluralize")args={"after":appsync.GraphqlType.string(),"first":appsync.GraphqlType.int(),"before":appsync.GraphqlType.string(),"last":appsync.GraphqlType.int()}Node=appsync.InterfaceType("Node",definition={"id":appsync.GraphqlType.string()})FilmNode=appsync.ObjectType("FilmNode",interface_types=[Node],definition={"film_name":appsync.GraphqlType.string()})defgenerate_edge_and_connection(base):edge=appsync.ObjectType(f"{base.name}Edge",definition={"node":base.attribute(),"cursor":appsync.GraphqlType.string()})connection=appsync.ObjectType(f"{base.name}Connection",definition={"edges":edge.attribute(is_list=True),"pluralize(base.name)":base.attribute(is_list=True),"total_count":appsync.GraphqlType.int()})return{"edge":edge,"connection":connection}Finally, we will go to ourcdk-stackand combine everything together
to generate our schema.# dummy_request: appsync.MappingTemplate# dummy_response: appsync.MappingTemplateapi=appsync.GraphqlApi(self,"Api",name="demo")object_types=[Node,FilmNode]film_connections=generate_edge_and_connection(FilmNode)api.add_query("allFilms",appsync.ResolvableField(return_type=film_connections.connection.attribute(),args=args,data_source=api.add_none_data_source("none"),request_mapping_template=dummy_request,response_mapping_template=dummy_response))api.add_type(Node)api.add_type(FilmNode)api.add_type(film_connections.edge)api.add_type(film_connections.connection)Notice how we can utilize thegenerateEdgeAndConnectionfunction to generate
Object Types. In the future, if we wanted to create more Object Types, we can simply
create the base Object Type (i.e. Film) and from there we can generate its respectiveConnectionsandEdges.Check out a more in-depth examplehere.GraphQL TypesOne of the benefits of GraphQL is its strongly typed nature. We define the
types within an object, query, mutation, interface, etc. asGraphQL Types.GraphQL Types are the building blocks of types, whether they are scalar, objects,
interfaces, etc. GraphQL Types can be:Scalar Types: Id, Int, String, AWSDate, etc.Object Types: types that you generate (i.e.demofrom the example above)Interface Types: abstract types that define the base implementation of other
Intermediate TypesMore concretely, GraphQL Types are simply the types appended to variables.
Referencing the object typeDemoin the previous example, the GraphQL Types
isString!and is applied to both the namesidandversion.DirectivesDirectivesare attached to a field or type and affect the execution of queries,
mutations, and types. With AppSync, we useDirectivesto configure authorization.
CDK provides static functions to add directives to your Schema.Directive.iam()sets a type or field's authorization to be validated throughIamDirective.apiKey()sets a type or field's authorization to be validated through aApi KeyDirective.oidc()sets a type or field's authorization to be validated throughOpenID ConnectDirective.cognito(...groups: string[])sets a type or field's authorization to be validated
throughCognito User Poolsgroupsthe name of the cognito groups to give accessTo learn more about authorization and directives, read these docshere.Field and Resolvable FieldsWhileGraphqlTypeis a base implementation for GraphQL fields, we have abstractions
on top ofGraphqlTypethat provide finer grain support.FieldFieldextendsGraphqlTypeand will allow you to define arguments.Interface Typesare not resolvable and this class will allow you to define arguments,
but not its resolvers.For example, if we want to create the following type:type Node {
  test(argument: string): String
}The CDK code required would be:field=appsync.Field(return_type=appsync.GraphqlType.string(),args={"argument":appsync.GraphqlType.string()})type=appsync.InterfaceType("Node",definition={"test":field})Resolvable FieldsResolvableFieldextendsFieldand will allow you to define arguments and its resolvers.Object Typescan have fields that resolve and perform operations on
your backend.You can also create resolvable fields for object types.type Info {
  node(id: String): String
}The CDK code required would be:# api: appsync.GraphqlApi# dummy_request: appsync.MappingTemplate# dummy_response: appsync.MappingTemplateinfo=appsync.ObjectType("Info",definition={"node":appsync.ResolvableField(return_type=appsync.GraphqlType.string(),args={"id":appsync.GraphqlType.string()},data_source=api.add_none_data_source("none"),request_mapping_template=dummy_request,response_mapping_template=dummy_response)})To nest resolvers, we can also create top level query types that call upon
other types. Building off the previous example, if we want the following graphql
type definition:type Query {
  get(argument: string): Info
}The CDK code required would be:# api: appsync.GraphqlApi# dummy_request: appsync.MappingTemplate# dummy_response: appsync.MappingTemplatequery=appsync.ObjectType("Query",definition={"get":appsync.ResolvableField(return_type=appsync.GraphqlType.string(),args={"argument":appsync.GraphqlType.string()},data_source=api.add_none_data_source("none"),request_mapping_template=dummy_request,response_mapping_template=dummy_response)})Learn more about fields and resolvershere.Intermediate TypesIntermediate Types are defined by Graphql Types and Fields. They have a set of defined
fields, where each field corresponds to another type in the system. Intermediate
Types will be the meat of your GraphQL Schema as they are the types defined by you.Intermediate Types include:Interface TypesObject TypesEnum TypesInput TypesUnion TypesInterface TypesInterface Typesare abstract types that define the implementation of other
intermediate types. They are useful for eliminating duplication and can be used
to generate Object Types with less work.You can create Interface Typesexternally.node=appsync.InterfaceType("Node",definition={"id":appsync.GraphqlType.string(is_required=True)})To learn more aboutInterface Types, read the docshere.Object TypesObject Typesare types that you declare. For example, in thecode-first examplethedemovariable is anObject Type.Object Typesare defined by
GraphQL Types and are only usable when linked to a GraphQL Api.You can create Object Types in two ways:Object Types can be createdexternally.api=appsync.GraphqlApi(self,"Api",name="demo")demo=appsync.ObjectType("Demo",definition={"id":appsync.GraphqlType.string(is_required=True),"version":appsync.GraphqlType.string(is_required=True)})api.add_type(demo)This method allows for reusability and modularity, ideal for larger projects.
For example, imagine moving all Object Type definition outside the stack.object-types.ts- a file for object type definitionsimportaws_cdk.aws_appsyncasappsyncdemo=appsync.ObjectType("Demo",definition={"id":appsync.GraphqlType.string(is_required=True),"version":appsync.GraphqlType.string(is_required=True)})cdk-stack.ts- a file containing our cdk stack# api: appsync.GraphqlApiapi.add_type(demo)Object Types can be createdexternallyfrom an Interface Type.node=appsync.InterfaceType("Node",definition={"id":appsync.GraphqlType.string(is_required=True)})demo=appsync.ObjectType("Demo",interface_types=[node],definition={"version":appsync.GraphqlType.string(is_required=True)})This method allows for reusability and modularity, ideal for reducing code duplication.To learn more aboutObject Types, read the docshere.Enum TypesEnum Typesare a special type of Intermediate Type. They restrict a particular
set of allowed values for other Intermediate Types.enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}This means that wherever we use the type Episode in our schema, we expect it to
be exactly one of NEWHOPE, EMPIRE, or JEDI.The above GraphQL Enumeration Type can be expressed in CDK as the following:# api: appsync.GraphqlApiepisode=appsync.EnumType("Episode",definition=["NEWHOPE","EMPIRE","JEDI"])api.add_type(episode)To learn more aboutEnum Types, read the docshere.Input TypesInput Typesare special types of Intermediate Types. They give users an
easy way to pass complex objects for top level Mutation and Queries.input Review {
  stars: Int!
  commentary: String
}The above GraphQL Input Type can be expressed in CDK as the following:# api: appsync.GraphqlApireview=appsync.InputType("Review",definition={"stars":appsync.GraphqlType.int(is_required=True),"commentary":appsync.GraphqlType.string()})api.add_type(review)To learn more aboutInput Types, read the docshere.Union TypesUnion Typesare a special type of Intermediate Type. They are similar to
Interface Types, but they cannot specify any common fields between types.Note:the fields of a union type need to beObject Types. In other words, you
can't create a union type out of interfaces, other unions, or inputs.union Search = Human | Droid | StarshipThe above GraphQL Union Type encompasses the Object Types of Human, Droid and Starship. It
can be expressed in CDK as the following:# api: appsync.GraphqlApistring=appsync.GraphqlType.string()human=appsync.ObjectType("Human",definition={"name":string})droid=appsync.ObjectType("Droid",definition={"name":string})starship=appsync.ObjectType("Starship",definition={"name":string})search=appsync.UnionType("Search",definition=[human,droid,starship])api.add_type(search)To learn more aboutUnion Types, read the docshere.QueryEvery schema requires a top level Query type. By default, the schema will look
for theObject TypenamedQuery. The top levelQueryis theonlyexposed
type that users can access to performGEToperations on your Api.To add fields for these queries, we can simply run theaddQueryfunction to add
to the schema'sQuerytype.# api: appsync.GraphqlApi# film_connection: appsync.InterfaceType# dummy_request: appsync.MappingTemplate# dummy_response: appsync.MappingTemplatestring=appsync.GraphqlType.string()int=appsync.GraphqlType.int()api.add_query("allFilms",appsync.ResolvableField(return_type=film_connection.attribute(),args={"after":string,"first":int,"before":string,"last":int},data_source=api.add_none_data_source("none"),request_mapping_template=dummy_request,response_mapping_template=dummy_response))To learn more about top level operations, check out the docshere.MutationEvery schemacanhave a top level Mutation type. By default, the schema will look
for theObjectTypenamedMutation. The top levelMutationType is the only exposed
type that users can access to performmutableoperations on your Api.To add fields for these mutations, we can simply run theaddMutationfunction to add
to the schema'sMutationtype.# api: appsync.GraphqlApi# film_node: appsync.ObjectType# dummy_request: appsync.MappingTemplate# dummy_response: appsync.MappingTemplatestring=appsync.GraphqlType.string()int=appsync.GraphqlType.int()api.add_mutation("addFilm",appsync.ResolvableField(return_type=film_node.attribute(),args={"name":string,"film_number":int},data_source=api.add_none_data_source("none"),request_mapping_template=dummy_request,response_mapping_template=dummy_response))To learn more about top level operations, check out the docshere.SubscriptionEvery schemacanhave a top level Subscription type. The top levelSubscriptionType
is the only exposed type that users can access to invoke a response to a mutation.Subscriptionsnotify users when a mutation specific mutation is called. This means you can make any data source
real time by specify a GraphQL Schema directive on a mutation.Note: The AWS AppSync client SDK automatically handles subscription connection management.To add fields for these subscriptions, we can simply run theaddSubscriptionfunction to add
to the schema'sSubscriptiontype.# api: appsync.GraphqlApi# film: appsync.InterfaceTypeapi.add_subscription("addedFilm",appsync.Field(return_type=film.attribute(),args={"id":appsync.GraphqlType.id(is_required=True)},directives=[appsync.Directive.subscribe("addFilm")]))To learn more about top level operations, check out the docshere.