Show / Hide Table of Contents

Namespace Amazon.CDK.AWS.AppSync

AWS AppSync Construct Library

--- End-of-Support
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 the Migrating to AWS CDK v2 guide.


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

using Amazon.CDK.AWS.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:

var api = new GraphqlApi(this, "Api", new GraphqlApiProps {
    Name = "demo",
    Schema = Schema.FromAsset(Join(__dirname, "schema.graphql")),
    AuthorizationConfig = new AuthorizationConfig {
        DefaultAuthorization = new AuthorizationMode {
            AuthorizationType = AuthorizationType.IAM
        }
    },
    XrayEnabled = true
});

var demoTable = new Table(this, "DemoTable", new TableProps {
    PartitionKey = new Attribute {
        Name = "id",
        Type = AttributeType.STRING
    }
});

var demoDS = api.AddDynamoDbDataSource("demoDataSource", demoTable);

// Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
demoDS.CreateResolver(new BaseResolverProps {
    TypeName = "Query",
    FieldName = "getDemos",
    RequestMappingTemplate = MappingTemplate.DynamoDbScanTable(),
    ResponseMappingTemplate = MappingTemplate.DynamoDbResultList()
});

// Resolver for the Mutation "addDemo" that puts the item into the DynamoDb table.
demoDS.CreateResolver(new BaseResolverProps {
    TypeName = "Mutation",
    FieldName = "addDemo",
    RequestMappingTemplate = MappingTemplate.DynamoDbPutItem(PrimaryKey.Partition("id").Auto(), Values.Projecting("input")),
    ResponseMappingTemplate = MappingTemplate.DynamoDbResultItem()
});

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
var secret = new DatabaseSecret(this, "AuroraSecret", new DatabaseSecretProps {
    Username = "clusteradmin"
});

// The VPC to place the cluster in
var vpc = new Vpc(this, "AuroraVpc");

// Create the serverless cluster, provide all values needed to customise the database.
var cluster = new ServerlessCluster(this, "AuroraCluster", new ServerlessClusterProps {
    Engine = DatabaseClusterEngine.AURORA_MYSQL,
    Vpc = vpc,
    Credentials = new Dictionary<string, string> { { "username", "clusteradmin" } },
    ClusterIdentifier = "db-endpoint-test",
    DefaultDatabaseName = "demos"
});
var rdsDS = api.AddRdsDataSource("rds", cluster, secret, "demos");

// Set up a resolver for an RDS query.
rdsDS.CreateResolver(new BaseResolverProps {
    TypeName = "Query",
    FieldName = "getDemosRds",
    RequestMappingTemplate = MappingTemplate.FromString(@"
      {
        ""version"": ""2018-05-29"",
        ""statements"": [
          ""SELECT * FROM demos""
        ]
      }
      "),
    ResponseMappingTemplate = MappingTemplate.FromString(@"
        $utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
      ")
});

// Set up a resolver for an RDS mutation.
rdsDS.CreateResolver(new BaseResolverProps {
    TypeName = "Mutation",
    FieldName = "addDemoRds",
    RequestMappingTemplate = MappingTemplate.FromString(@"
      {
        ""version"": ""2018-05-29"",
        ""statements"": [
          ""INSERT INTO demos VALUES (:id, :version)"",
          ""SELECT * WHERE id = :id""
        ],
        ""variableMap"": {
          "":id"": $util.toJson($util.autoId()),
          "":version"": $util.toJson($ctx.args.version)
        }
      }
      "),
    ResponseMappingTemplate = MappingTemplate.FromString(@"
        $utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
      ")
});

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:

var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "api",
    Schema = Schema.FromAsset(Join(__dirname, "schema.graphql"))
});

var httpDs = api.AddHttpDataSource("ds", "https://states.amazonaws.com", new HttpDataSourceOptions {
    Name = "httpDsWithStepF",
    Description = "from appsync to StepFunctions Workflow",
    AuthorizationConfig = new AwsIamConfig {
        SigningRegion = "us-east-1",
        SigningServiceName = "states"
    }
});

httpDs.CreateResolver(new BaseResolverProps {
    TypeName = "Mutation",
    FieldName = "callStepFunction",
    RequestMappingTemplate = MappingTemplate.FromFile("request.vtl"),
    ResponseMappingTemplate = MappingTemplate.FromFile("response.vtl")
});

Amazon OpenSearch Service

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

using Amazon.CDK.AWS.OpenSearchService;

GraphqlApi api;


var user = new User(this, "User");
var domain = new Domain(this, "Domain", new DomainProps {
    Version = EngineVersion.OPENSEARCH_1_2,
    RemovalPolicy = RemovalPolicy.DESTROY,
    FineGrainedAccessControl = new AdvancedSecurityOptions { MasterUserArn = user.UserArn },
    EncryptionAtRest = new EncryptionAtRestOptions { Enabled = true },
    NodeToNodeEncryption = true,
    EnforceHttps = true
});
var ds = api.AddOpenSearchDataSource("ds", domain);

ds.CreateResolver(new BaseResolverProps {
    TypeName = "Query",
    FieldName = "getTests",
    RequestMappingTemplate = MappingTemplate.FromString(JSON.Stringify(new Dictionary<string, object> {
        { "version", "2017-02-28" },
        { "operation", "GET" },
        { "path", "/id/post/_search" },
        { "params", new Struct {
            Headers = new Struct { },
            QueryString = new Struct { },
            Body = new Struct { From = 0, Size = 50 }
        } }
    })),
    ResponseMappingTemplate = MappingTemplate.FromString(@"[
        #foreach($entry in $context.result.hits.hits)
        #if( $velocityCount > 1 ) , #end
        $utils.toJson($entry.get(""_source""))
        #end
      ]")
});

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.

using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.Route53;

// hosted zone and route53 features
string hostedZoneId;
var zoneName = "example.com";


var myDomainName = "api.example.com";
var certificate = new Certificate(this, "cert", new CertificateProps { DomainName = myDomainName });
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "myApi",
    DomainName = new DomainOptions {
        Certificate = certificate,
        DomainName = myDomainName
    }
});

// hosted zone for adding appsync domain
var zone = HostedZone.FromHostedZoneAttributes(this, "HostedZone", new HostedZoneAttributes {
    HostedZoneId = hostedZoneId,
    ZoneName = zoneName
});

// create a cname to the appsync domain. will map to something like xxxx.cloudfront.net
// create a cname to the appsync domain. will map to something like xxxx.cloudfront.net
new CnameRecord(this, "CnameApiRecord", new CnameRecordProps {
    RecordName = "api",
    Zone = zone,
    DomainName = myDomainName
});

Schema

Every GraphQL Api needs a schema to define the Api. CDK offers appsync.Schema for static convenience methods for various types of schema declaration: code-first or schema-first.

Code-First

When declaring your GraphQL Api, CDK defaults to a code-first approach if the schema property is not configured.

var api = new GraphqlApi(this, "api", new GraphqlApiProps { Name = "myApi" });

CDK will declare a Schema class that will give your Api access functions to define your schema code-first: addType, addToSchema, etc.

You can also declare your Schema class outside of your CDK stack, to define your schema externally.

var schema = new Schema();
schema.AddType(new ObjectType("demo", new ObjectTypeOptions {
    Definition = new Dictionary<string, IField> { { "id", GraphqlType.Id() } }
}));
var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "myApi",
    Schema = schema
});

See the code-first schema section for more details.

Schema-First

You can define your GraphQL Schema from a file on disk. For convenience, use the appsync.Schema.fromAsset to specify the file representing your schema.

var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "myApi",
    Schema = Schema.FromAsset(Join(__dirname, "schema.graphl"))
});

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;

var importedApi = GraphqlApi.FromGraphqlApiAttributes(this, "IApi", new GraphqlApiAttributes {
    GraphqlApiId = api.ApiId,
    GraphqlApiArn = api.Arn
});
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.

Authorization

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

    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.

    using Amazon.CDK.AWS.Lambda;
    Function authFunction;
    
    
    new GraphqlApi(this, "api", new GraphqlApiProps {
        Name = "api",
        Schema = Schema.FromAsset(Join(__dirname, "appsync.test.graphql")),
        AuthorizationConfig = new AuthorizationConfig {
            DefaultAuthorization = new AuthorizationMode {
                AuthorizationType = AuthorizationType.LAMBDA,
                LambdaAuthorizerConfig = new LambdaAuthorizerConfig {
                    Handler = authFunction
                }
            }
        }
    });

    Permissions

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

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

    In schema.graphql:

    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;
    var role = new Role(this, "Role", new RoleProps {
        AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
    });
    
    api.Grant(role, IamResource.Custom("types/Mutation/fields/updateExample"), "appsync:GraphQL");

    IamResource

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

      Generic Permissions

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

      These include:

        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;
        
        
        var appsyncFunction = new AppsyncFunction(this, "function", new AppsyncFunctionProps {
            Name = "appsync_function",
            Api = api,
            DataSource = api.AddNoneDataSource("none"),
            RequestMappingTemplate = MappingTemplate.FromFile("request.vtl"),
            ResponseMappingTemplate = MappingTemplate.FromFile("response.vtl")
        });

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

        GraphqlApi api;
        AppsyncFunction appsyncFunction;
        
        
        var pipelineResolver = new Resolver(this, "pipeline", new ResolverProps {
            Api = api,
            DataSource = api.AddNoneDataSource("none"),
            TypeName = "typeName",
            FieldName = "fieldName",
            RequestMappingTemplate = MappingTemplate.FromFile("beforeRequest.vtl"),
            PipelineConfig = new [] { appsyncFunction },
            ResponseMappingTemplate = MappingTemplate.FromFile("afterResponse.vtl")
        });

        Learn more about Pipeline Resolvers and AppSync Functions here.

        Code-First Schema

        CDK offers the ability to generate your schema in a code-first approach. A code-first approach offers a developer workflow with:

          The code-first approach allows for dynamic schema generation. You can generate your schema based on variables and templates to reduce code duplication.

          Code-First Example

          To 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 query allFilms(first: 100) since FilmConnection acts as an intermediary for holding FilmEdges we 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 file object-types.ts and we will have created it in a way that allows us to generate other XxxConnection and XxxEdges in the future.

          using Amazon.CDK.AWS.AppSync;
          var pluralize = Require("pluralize");
          
          IDictionary<string, GraphqlType> args = new Dictionary<string, GraphqlType> {
              { "after", GraphqlType.String() },
              { "first", GraphqlType.Int() },
              { "before", GraphqlType.String() },
              { "last", GraphqlType.Int() }
          };
          
          var Node = new InterfaceType("Node", new IntermediateTypeOptions {
              Definition = new Dictionary<string, IField> { { "id", GraphqlType.String() } }
          });
          var FilmNode = new ObjectType("FilmNode", new ObjectTypeOptions {
              InterfaceTypes = new [] { Node },
              Definition = new Dictionary<string, IField> { { "filmName", GraphqlType.String() } }
          });
          
          public IDictionary<string, ObjectType> GenerateEdgeAndConnection(ObjectType base)
          {
              var edge = new ObjectType($"{base.name}Edge", new ObjectTypeOptions {
                  Definition = new Dictionary<string, IField> { { "node", base.Attribute() }, { "cursor", GraphqlType.String() } }
              });
              var connection = new ObjectType($"{base.name}Connection", new ObjectTypeOptions {
                  Definition = new Dictionary<string, IField> {
                      { "edges", edge.Attribute(new BaseTypeOptions { IsList = true }) },
                      { Pluralize(base.Name), base.Attribute(new BaseTypeOptions { IsList = true }) },
                      { "totalCount", GraphqlType.Int() }
                  }
              });
              return new Struct { Edge = edge, Connection = connection };
          }

          Finally, we will go to our cdk-stack and combine everything together to generate our schema.

          MappingTemplate dummyRequest;
          MappingTemplate dummyResponse;
          
          
          var api = new GraphqlApi(this, "Api", new GraphqlApiProps {
              Name = "demo"
          });
          
          var objectTypes = new [] { Node, FilmNode };
          
          IDictionary<string, ObjectType> filmConnections = GenerateEdgeAndConnection(FilmNode);
          
          api.AddQuery("allFilms", new ResolvableField(new ResolvableFieldOptions {
              ReturnType = filmConnections.Connection.Attribute(),
              Args = args,
              DataSource = api.AddNoneDataSource("none"),
              RequestMappingTemplate = dummyRequest,
              ResponseMappingTemplate = dummyResponse
          }));
          
          api.AddType(Node);
          api.AddType(FilmNode);
          api.AddType(filmConnections.Edge);
          api.AddType(filmConnections.Connection);

          Notice how we can utilize the generateEdgeAndConnection function 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 respective Connections and Edges.

          Check out a more in-depth example here.

          GraphQL Types

          One of the benefits of GraphQL is its strongly typed nature. We define the types within an object, query, mutation, interface, etc. as GraphQL Types.

          GraphQL Types are the building blocks of types, whether they are scalar, objects, interfaces, etc. GraphQL Types can be:

            More concretely, GraphQL Types are simply the types appended to variables. Referencing the object type Demo in the previous example, the GraphQL Types is String! and is applied to both the names id and version.

            Directives

            Directives are attached to a field or type and affect the execution of queries, mutations, and types. With AppSync, we use Directives to configure authorization. CDK provides static functions to add directives to your Schema.

              To learn more about authorization and directives, read these docs here.

              Field and Resolvable Fields

              While GraphqlType is a base implementation for GraphQL fields, we have abstractions on top of GraphqlType that provide finer grain support.

              Field

              Field extends GraphqlType and will allow you to define arguments. Interface Types are 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:

              var field = new Field(new FieldOptions {
                  ReturnType = GraphqlType.String(),
                  Args = new Dictionary<string, GraphqlType> {
                      { "argument", GraphqlType.String() }
                  }
              });
              var type = new InterfaceType("Node", new IntermediateTypeOptions {
                  Definition = new Dictionary<string, IField> { { "test", field } }
              });

              Resolvable Fields

              ResolvableField extends Field and will allow you to define arguments and its resolvers. Object Types can 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:

              GraphqlApi api;
              MappingTemplate dummyRequest;
              MappingTemplate dummyResponse;
              
              var info = new ObjectType("Info", new ObjectTypeOptions {
                  Definition = new Dictionary<string, IField> {
                      { "node", new ResolvableField(new ResolvableFieldOptions {
                          ReturnType = GraphqlType.String(),
                          Args = new Dictionary<string, GraphqlType> {
                              { "id", GraphqlType.String() }
                          },
                          DataSource = api.AddNoneDataSource("none"),
                          RequestMappingTemplate = dummyRequest,
                          ResponseMappingTemplate = dummyResponse
                      }) }
                  }
              });

              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:

              GraphqlApi api;
              MappingTemplate dummyRequest;
              MappingTemplate dummyResponse;
              
              var query = new ObjectType("Query", new ObjectTypeOptions {
                  Definition = new Dictionary<string, IField> {
                      { "get", new ResolvableField(new ResolvableFieldOptions {
                          ReturnType = GraphqlType.String(),
                          Args = new Dictionary<string, GraphqlType> {
                              { "argument", GraphqlType.String() }
                          },
                          DataSource = api.AddNoneDataSource("none"),
                          RequestMappingTemplate = dummyRequest,
                          ResponseMappingTemplate = dummyResponse
                      }) }
                  }
              });

              Learn more about fields and resolvers here.

              Intermediate Types

              Intermediate 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 Types

                Interface Types are 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 Types externally.

                var node = new InterfaceType("Node", new IntermediateTypeOptions {
                    Definition = new Dictionary<string, IField> {
                        { "id", GraphqlType.String(new BaseTypeOptions { IsRequired = true }) }
                    }
                });

                To learn more about Interface Types, read the docs here.

                Object Types

                Object Types are types that you declare. For example, in the code-first example the demo variable is an Object Type. Object Types are defined by GraphQL Types and are only usable when linked to a GraphQL Api.

                You can create Object Types in two ways:

                  To learn more about Object Types, read the docs here.

                  Enum Types

                  Enum Types are 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:

                  GraphqlApi api;
                  
                  var episode = new EnumType("Episode", new EnumTypeOptions {
                      Definition = new [] { "NEWHOPE", "EMPIRE", "JEDI" }
                  });
                  api.AddType(episode);

                  To learn more about Enum Types, read the docs here.

                  Input Types

                  Input Types are 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:

                  GraphqlApi api;
                  
                  var review = new InputType("Review", new IntermediateTypeOptions {
                      Definition = new Dictionary<string, IField> {
                          { "stars", GraphqlType.Int(new BaseTypeOptions { IsRequired = true }) },
                          { "commentary", GraphqlType.String() }
                      }
                  });
                  api.AddType(review);

                  To learn more about Input Types, read the docs here.

                  Union Types

                  Union Types are 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 be Object Types. In other words, you can't create a union type out of interfaces, other unions, or inputs.

                  union Search = Human | Droid | Starship

                  The above GraphQL Union Type encompasses the Object Types of Human, Droid and Starship. It can be expressed in CDK as the following:

                  GraphqlApi api;
                  
                  var string = GraphqlType.String();
                  var human = new ObjectType("Human", new ObjectTypeOptions { Definition = new Dictionary<string, IField> { { "name", string } } });
                  var droid = new ObjectType("Droid", new ObjectTypeOptions { Definition = new Dictionary<string, IField> { { "name", string } } });
                  var starship = new ObjectType("Starship", new ObjectTypeOptions { Definition = new Dictionary<string, IField> { { "name", string } } });
                  var search = new UnionType("Search", new UnionTypeOptions {
                      Definition = new [] { human, droid, starship }
                  });
                  api.AddType(search);

                  To learn more about Union Types, read the docs here.

                  Query

                  Every schema requires a top level Query type. By default, the schema will look for the Object Type named Query. The top level Query is the only exposed type that users can access to perform GET operations on your Api.

                  To add fields for these queries, we can simply run the addQuery function to add to the schema's Query type.

                  GraphqlApi api;
                  InterfaceType filmConnection;
                  MappingTemplate dummyRequest;
                  MappingTemplate dummyResponse;
                  
                  
                  var string = GraphqlType.String();
                  var int = GraphqlType.Int();
                  api.AddQuery("allFilms", new ResolvableField(new ResolvableFieldOptions {
                      ReturnType = filmConnection.Attribute(),
                      Args = new Dictionary<string, GraphqlType> { { "after", string }, { "first", int }, { "before", string }, { "last", int } },
                      DataSource = api.AddNoneDataSource("none"),
                      RequestMappingTemplate = dummyRequest,
                      ResponseMappingTemplate = dummyResponse
                  }));

                  To learn more about top level operations, check out the docs here.

                  Mutation

                  Every schema can have a top level Mutation type. By default, the schema will look for the ObjectType named Mutation. The top level Mutation Type is the only exposed type that users can access to perform mutable operations on your Api.

                  To add fields for these mutations, we can simply run the addMutation function to add to the schema's Mutation type.

                  GraphqlApi api;
                  ObjectType filmNode;
                  MappingTemplate dummyRequest;
                  MappingTemplate dummyResponse;
                  
                  
                  var string = GraphqlType.String();
                  var int = GraphqlType.Int();
                  api.AddMutation("addFilm", new ResolvableField(new ResolvableFieldOptions {
                      ReturnType = filmNode.Attribute(),
                      Args = new Dictionary<string, GraphqlType> { { "name", string }, { "film_number", int } },
                      DataSource = api.AddNoneDataSource("none"),
                      RequestMappingTemplate = dummyRequest,
                      ResponseMappingTemplate = dummyResponse
                  }));

                  To learn more about top level operations, check out the docs here.

                  Subscription

                  Every schema can have a top level Subscription type. The top level Subscription Type is the only exposed type that users can access to invoke a response to a mutation. Subscriptions notify 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 the addSubscription function to add to the schema's Subscription type.

                  GraphqlApi api;
                  InterfaceType film;
                  
                  
                  api.AddSubscription("addedFilm", new Field(new FieldOptions {
                      ReturnType = film.Attribute(),
                      Args = new Dictionary<string, GraphqlType> { { "id", GraphqlType.Id(new BaseTypeOptions { IsRequired = true }) } },
                      Directives = new [] { Directive.Subscribe("addFilm") }
                  }));

                  To learn more about top level operations, check out the docs here.

                  Classes

                  AddFieldOptions

                  (experimental) The options to add a field to an Intermediate Type.

                  ApiKeyConfig

                  (experimental) Configuration for API Key authorization in AppSync.

                  AppsyncFunction

                  (experimental) AppSync Functions are local functions that perform certain operations onto a backend data source.

                  AppsyncFunctionAttributes

                  (experimental) The attributes for imported AppSync Functions.

                  AppsyncFunctionProps

                  (experimental) the CDK properties for AppSync Functions.

                  Assign

                  (experimental) Utility class representing the assigment of a value to an attribute.

                  AttributeValues

                  (experimental) Specifies the attribute value assignments.

                  AttributeValuesStep

                  (experimental) Utility class to allow assigning a value to an attribute.

                  AuthorizationConfig

                  (experimental) Configuration of the API authorization modes.

                  AuthorizationMode

                  (experimental) Interface to specify default or additional authorization(s).

                  AuthorizationType

                  (experimental) enum with all possible values for AppSync authorization type.

                  AwsIamConfig

                  (experimental) The authorization config in case the HTTP endpoint requires authorization.

                  BackedDataSource

                  (experimental) Abstract AppSync datasource implementation.

                  BackedDataSourceProps

                  (experimental) properties for an AppSync datasource backed by a resource.

                  BaseAppsyncFunctionProps

                  (experimental) the base properties for AppSync Functions.

                  BaseDataSource

                  (experimental) Abstract AppSync datasource implementation.

                  BaseDataSourceProps

                  (experimental) Base properties for an AppSync datasource.

                  BaseResolverProps

                  (experimental) Basic properties for an AppSync resolver.

                  BaseTypeOptions

                  (experimental) Base options for GraphQL Types.

                  CachingConfig

                  (experimental) CachingConfig for AppSync resolvers.

                  CfnApiCache

                  A CloudFormation AWS::AppSync::ApiCache.

                  CfnApiCacheProps

                  Properties for defining a CfnApiCache.

                  CfnApiKey

                  A CloudFormation AWS::AppSync::ApiKey.

                  CfnApiKeyProps

                  Properties for defining a CfnApiKey.

                  CfnDataSource

                  A CloudFormation AWS::AppSync::DataSource.

                  CfnDataSource.AuthorizationConfigProperty

                  The AuthorizationConfig property type specifies the authorization type and configuration for an AWS AppSync http data source.

                  CfnDataSource.AwsIamConfigProperty

                  Use the AwsIamConfig property type to specify AwsIamConfig for a AWS AppSync authorizaton.

                  CfnDataSource.DeltaSyncConfigProperty

                  Describes a Delta Sync configuration.

                  CfnDataSource.DynamoDBConfigProperty

                  The DynamoDBConfig property type specifies the AwsRegion and TableName for an Amazon DynamoDB table in your account for an AWS AppSync data source.

                  CfnDataSource.ElasticsearchConfigProperty

                  The ElasticsearchConfig property type specifies the AwsRegion and Endpoints for an Amazon OpenSearch Service domain in your account for an AWS AppSync data source.

                  CfnDataSource.EventBridgeConfigProperty

                  The data source.

                  CfnDataSource.HttpConfigProperty

                  Use the HttpConfig property type to specify HttpConfig for an AWS AppSync data source.

                  CfnDataSource.LambdaConfigProperty

                  The LambdaConfig property type specifies the Lambda function ARN for an AWS AppSync data source.

                  CfnDataSource.OpenSearchServiceConfigProperty

                  The OpenSearchServiceConfig property type specifies the AwsRegion and Endpoints for an Amazon OpenSearch Service domain in your account for an AWS AppSync data source.

                  CfnDataSource.RdsHttpEndpointConfigProperty

                  Use the RdsHttpEndpointConfig property type to specify the RdsHttpEndpoint for an AWS AppSync relational database.

                  CfnDataSource.RelationalDatabaseConfigProperty

                  Use the RelationalDatabaseConfig property type to specify RelationalDatabaseConfig for an AWS AppSync data source.

                  CfnDataSourceProps

                  Properties for defining a CfnDataSource.

                  CfnDomainName

                  A CloudFormation AWS::AppSync::DomainName.

                  CfnDomainNameApiAssociation

                  A CloudFormation AWS::AppSync::DomainNameApiAssociation.

                  CfnDomainNameApiAssociationProps

                  Properties for defining a CfnDomainNameApiAssociation.

                  CfnDomainNameProps

                  Properties for defining a CfnDomainName.

                  CfnFunctionConfiguration

                  A CloudFormation AWS::AppSync::FunctionConfiguration.

                  CfnFunctionConfiguration.AppSyncRuntimeProperty

                  Describes a runtime used by an AWS AppSync pipeline resolver or AWS AppSync function.

                  CfnFunctionConfiguration.LambdaConflictHandlerConfigProperty

                  The LambdaConflictHandlerConfig object when configuring LAMBDA as the Conflict Handler.

                  CfnFunctionConfiguration.SyncConfigProperty

                  Describes a Sync configuration for a resolver.

                  CfnFunctionConfigurationProps

                  Properties for defining a CfnFunctionConfiguration.

                  CfnGraphQLApi

                  A CloudFormation AWS::AppSync::GraphQLApi.

                  CfnGraphQLApi.AdditionalAuthenticationProviderProperty

                  Describes an additional authentication provider.

                  CfnGraphQLApi.CognitoUserPoolConfigProperty

                  Describes an Amazon Cognito user pool configuration.

                  CfnGraphQLApi.LambdaAuthorizerConfigProperty

                  Configuration for AWS Lambda function authorization.

                  CfnGraphQLApi.LogConfigProperty

                  The LogConfig property type specifies the logging configuration when writing GraphQL operations and tracing to Amazon CloudWatch for an AWS AppSync GraphQL API.

                  CfnGraphQLApi.OpenIDConnectConfigProperty

                  The OpenIDConnectConfig property type specifies the optional authorization configuration for using an OpenID Connect compliant service with your GraphQL endpoint for an AWS AppSync GraphQL API.

                  CfnGraphQLApi.UserPoolConfigProperty

                  The UserPoolConfig property type specifies the optional authorization configuration for using Amazon Cognito user pools with your GraphQL endpoint for an AWS AppSync GraphQL API.

                  CfnGraphQLApiProps

                  Properties for defining a CfnGraphQLApi.

                  CfnGraphQLSchema

                  A CloudFormation AWS::AppSync::GraphQLSchema.

                  CfnGraphQLSchemaProps

                  Properties for defining a CfnGraphQLSchema.

                  CfnResolver

                  A CloudFormation AWS::AppSync::Resolver.

                  CfnResolver.AppSyncRuntimeProperty

                  Describes a runtime used by an AWS AppSync pipeline resolver or AWS AppSync function.

                  CfnResolver.CachingConfigProperty

                  The caching configuration for a resolver that has caching activated.

                  CfnResolver.LambdaConflictHandlerConfigProperty

                  The LambdaConflictHandlerConfig when configuring LAMBDA as the Conflict Handler.

                  CfnResolver.PipelineConfigProperty

                  Use the PipelineConfig property type to specify PipelineConfig for an AWS AppSync resolver.

                  CfnResolver.SyncConfigProperty

                  Describes a Sync configuration for a resolver.

                  CfnResolverProps

                  Properties for defining a CfnResolver.

                  CfnSourceApiAssociation

                  A CloudFormation AWS::AppSync::SourceApiAssociation.

                  CfnSourceApiAssociation.SourceApiAssociationConfigProperty

                  Describes properties used to specify configurations related to a source API.

                  CfnSourceApiAssociationProps

                  Properties for defining a CfnSourceApiAssociation.

                  DataSourceOptions

                  (experimental) Optional configuration for data sources.

                  Directive

                  (experimental) Directives for types.

                  DomainOptions

                  (experimental) Domain name configuration for AppSync.

                  DynamoDbDataSource

                  (experimental) An AppSync datasource backed by a DynamoDB table.

                  DynamoDbDataSourceProps

                  (experimental) Properties for an AppSync DynamoDB datasource.

                  ElasticsearchDataSource

                  (deprecated) An Appsync datasource backed by Elasticsearch.

                  ElasticsearchDataSourceProps

                  (deprecated) Properties for the Elasticsearch Data Source.

                  EnumType

                  (experimental) Enum Types are abstract types that includes a set of fields that represent the strings this type can create.

                  EnumTypeOptions

                  (experimental) Properties for configuring an Enum Type.

                  ExtendedDataSourceProps

                  (experimental) props used by implementations of BaseDataSource to provide configuration.

                  ExtendedResolverProps

                  (experimental) Additional property for an AppSync resolver for data source reference.

                  Field

                  (experimental) Fields build upon Graphql Types and provide typing and arguments.

                  FieldLogLevel

                  (experimental) log-level for fields in AppSync.

                  FieldOptions

                  (experimental) Properties for configuring a field.

                  GraphqlApi

                  (experimental) An AppSync GraphQL API.

                  GraphqlApiAttributes

                  (experimental) Attributes for GraphQL imports.

                  GraphqlApiBase

                  (experimental) Base Class for GraphQL API.

                  GraphqlApiProps

                  (experimental) Properties for an AppSync GraphQL API.

                  GraphqlType

                  (experimental) The GraphQL Types in AppSync's GraphQL.

                  GraphqlTypeOptions

                  (experimental) Options for GraphQL Types.

                  HttpDataSource

                  (experimental) An AppSync datasource backed by a http endpoint.

                  HttpDataSourceOptions

                  (experimental) Optional configuration for Http data sources.

                  HttpDataSourceProps

                  (experimental) Properties for an AppSync http datasource.

                  IamResource

                  (experimental) A class used to generate resource arns for AppSync.

                  InputType

                  (experimental) Input Types are abstract types that define complex objects.

                  InterfaceType

                  (experimental) Interface Types are abstract types that includes a certain set of fields that other types must include if they implement the interface.

                  IntermediateTypeOptions

                  (experimental) Properties for configuring an Intermediate Type.

                  KeyCondition

                  (experimental) Factory class for DynamoDB key conditions.

                  LambdaAuthorizerConfig

                  (experimental) Configuration for Lambda authorization in AppSync.

                  LambdaDataSource

                  (experimental) An AppSync datasource backed by a Lambda function.

                  LambdaDataSourceProps

                  (experimental) Properties for an AppSync Lambda datasource.

                  LogConfig

                  (experimental) Logging configuration for AppSync.

                  MappingTemplate

                  (experimental) MappingTemplates for AppSync resolvers.

                  NoneDataSource

                  (experimental) An AppSync dummy datasource.

                  NoneDataSourceProps

                  (experimental) Properties for an AppSync dummy datasource.

                  ObjectType

                  (experimental) Object Types are types declared by you.

                  ObjectTypeOptions

                  (experimental) Properties for configuring an Object Type.

                  OpenIdConnectConfig

                  (experimental) Configuration for OpenID Connect authorization in AppSync.

                  OpenSearchDataSource

                  (experimental) An Appsync datasource backed by OpenSearch.

                  OpenSearchDataSourceProps

                  (experimental) Properties for the OpenSearch Data Source.

                  PartitionKey

                  (experimental) Specifies the assignment to the partition key.

                  PartitionKeyStep

                  (experimental) Utility class to allow assigning a value or an auto-generated id to a partition key.

                  PrimaryKey

                  (experimental) Specifies the assignment to the primary key.

                  RdsDataSource

                  (experimental) An AppSync datasource backed by RDS.

                  RdsDataSourceProps

                  (experimental) Properties for an AppSync RDS datasource.

                  ResolvableField

                  (experimental) Resolvable Fields build upon Graphql Types and provide fields that can resolve into operations on a data source.

                  ResolvableFieldOptions

                  (experimental) Properties for configuring a resolvable field.

                  Resolver

                  (experimental) An AppSync resolver.

                  ResolverProps

                  (experimental) Additional property for an AppSync resolver for GraphQL API reference.

                  Schema

                  (experimental) The Schema for a GraphQL Api.

                  SchemaOptions

                  (experimental) The options for configuring a schema.

                  SortKeyStep

                  (experimental) Utility class to allow assigning a value or an auto-generated id to a sort key.

                  Type

                  (experimental) Enum containing the Types that can be used to define ObjectTypes.

                  UnionType

                  (experimental) Union Types are abstract types that are similar to Interface Types, but they cannot to specify any common fields between types.

                  UnionTypeOptions

                  (experimental) Properties for configuring an Union Type.

                  UserPoolConfig

                  (experimental) Configuration for Cognito user-pools in AppSync.

                  UserPoolDefaultAction

                  (experimental) enum with all possible values for Cognito user-pool default actions.

                  Values

                  (experimental) Factory class for attribute value assignments.

                  Interfaces

                  CfnDataSource.IAuthorizationConfigProperty

                  The AuthorizationConfig property type specifies the authorization type and configuration for an AWS AppSync http data source.

                  CfnDataSource.IAwsIamConfigProperty

                  Use the AwsIamConfig property type to specify AwsIamConfig for a AWS AppSync authorizaton.

                  CfnDataSource.IDeltaSyncConfigProperty

                  Describes a Delta Sync configuration.

                  CfnDataSource.IDynamoDBConfigProperty

                  The DynamoDBConfig property type specifies the AwsRegion and TableName for an Amazon DynamoDB table in your account for an AWS AppSync data source.

                  CfnDataSource.IElasticsearchConfigProperty

                  The ElasticsearchConfig property type specifies the AwsRegion and Endpoints for an Amazon OpenSearch Service domain in your account for an AWS AppSync data source.

                  CfnDataSource.IEventBridgeConfigProperty

                  The data source.

                  CfnDataSource.IHttpConfigProperty

                  Use the HttpConfig property type to specify HttpConfig for an AWS AppSync data source.

                  CfnDataSource.ILambdaConfigProperty

                  The LambdaConfig property type specifies the Lambda function ARN for an AWS AppSync data source.

                  CfnDataSource.IOpenSearchServiceConfigProperty

                  The OpenSearchServiceConfig property type specifies the AwsRegion and Endpoints for an Amazon OpenSearch Service domain in your account for an AWS AppSync data source.

                  CfnDataSource.IRdsHttpEndpointConfigProperty

                  Use the RdsHttpEndpointConfig property type to specify the RdsHttpEndpoint for an AWS AppSync relational database.

                  CfnDataSource.IRelationalDatabaseConfigProperty

                  Use the RelationalDatabaseConfig property type to specify RelationalDatabaseConfig for an AWS AppSync data source.

                  CfnFunctionConfiguration.IAppSyncRuntimeProperty

                  Describes a runtime used by an AWS AppSync pipeline resolver or AWS AppSync function.

                  CfnFunctionConfiguration.ILambdaConflictHandlerConfigProperty

                  The LambdaConflictHandlerConfig object when configuring LAMBDA as the Conflict Handler.

                  CfnFunctionConfiguration.ISyncConfigProperty

                  Describes a Sync configuration for a resolver.

                  CfnGraphQLApi.IAdditionalAuthenticationProviderProperty

                  Describes an additional authentication provider.

                  CfnGraphQLApi.ICognitoUserPoolConfigProperty

                  Describes an Amazon Cognito user pool configuration.

                  CfnGraphQLApi.ILambdaAuthorizerConfigProperty

                  Configuration for AWS Lambda function authorization.

                  CfnGraphQLApi.ILogConfigProperty

                  The LogConfig property type specifies the logging configuration when writing GraphQL operations and tracing to Amazon CloudWatch for an AWS AppSync GraphQL API.

                  CfnGraphQLApi.IOpenIDConnectConfigProperty

                  The OpenIDConnectConfig property type specifies the optional authorization configuration for using an OpenID Connect compliant service with your GraphQL endpoint for an AWS AppSync GraphQL API.

                  CfnGraphQLApi.IUserPoolConfigProperty

                  The UserPoolConfig property type specifies the optional authorization configuration for using Amazon Cognito user pools with your GraphQL endpoint for an AWS AppSync GraphQL API.

                  CfnResolver.IAppSyncRuntimeProperty

                  Describes a runtime used by an AWS AppSync pipeline resolver or AWS AppSync function.

                  CfnResolver.ICachingConfigProperty

                  The caching configuration for a resolver that has caching activated.

                  CfnResolver.ILambdaConflictHandlerConfigProperty

                  The LambdaConflictHandlerConfig when configuring LAMBDA as the Conflict Handler.

                  CfnResolver.IPipelineConfigProperty

                  Use the PipelineConfig property type to specify PipelineConfig for an AWS AppSync resolver.

                  CfnResolver.ISyncConfigProperty

                  Describes a Sync configuration for a resolver.

                  CfnSourceApiAssociation.ISourceApiAssociationConfigProperty

                  Describes properties used to specify configurations related to a source API.

                  IAddFieldOptions

                  (experimental) The options to add a field to an Intermediate Type.

                  IApiKeyConfig

                  (experimental) Configuration for API Key authorization in AppSync.

                  IAppsyncFunction

                  (experimental) Interface for AppSync Functions.

                  IAppsyncFunctionAttributes

                  (experimental) The attributes for imported AppSync Functions.

                  IAppsyncFunctionProps

                  (experimental) the CDK properties for AppSync Functions.

                  IAuthorizationConfig

                  (experimental) Configuration of the API authorization modes.

                  IAuthorizationMode

                  (experimental) Interface to specify default or additional authorization(s).

                  IAwsIamConfig

                  (experimental) The authorization config in case the HTTP endpoint requires authorization.

                  IBackedDataSourceProps

                  (experimental) properties for an AppSync datasource backed by a resource.

                  IBaseAppsyncFunctionProps

                  (experimental) the base properties for AppSync Functions.

                  IBaseDataSourceProps

                  (experimental) Base properties for an AppSync datasource.

                  IBaseResolverProps

                  (experimental) Basic properties for an AppSync resolver.

                  IBaseTypeOptions

                  (experimental) Base options for GraphQL Types.

                  ICachingConfig

                  (experimental) CachingConfig for AppSync resolvers.

                  ICfnApiCacheProps

                  Properties for defining a CfnApiCache.

                  ICfnApiKeyProps

                  Properties for defining a CfnApiKey.

                  ICfnDataSourceProps

                  Properties for defining a CfnDataSource.

                  ICfnDomainNameApiAssociationProps

                  Properties for defining a CfnDomainNameApiAssociation.

                  ICfnDomainNameProps

                  Properties for defining a CfnDomainName.

                  ICfnFunctionConfigurationProps

                  Properties for defining a CfnFunctionConfiguration.

                  ICfnGraphQLApiProps

                  Properties for defining a CfnGraphQLApi.

                  ICfnGraphQLSchemaProps

                  Properties for defining a CfnGraphQLSchema.

                  ICfnResolverProps

                  Properties for defining a CfnResolver.

                  ICfnSourceApiAssociationProps

                  Properties for defining a CfnSourceApiAssociation.

                  IDataSourceOptions

                  (experimental) Optional configuration for data sources.

                  IDomainOptions

                  (experimental) Domain name configuration for AppSync.

                  IDynamoDbDataSourceProps

                  (experimental) Properties for an AppSync DynamoDB datasource.

                  IElasticsearchDataSourceProps

                  (deprecated) Properties for the Elasticsearch Data Source.

                  IEnumTypeOptions

                  (experimental) Properties for configuring an Enum Type.

                  IExtendedDataSourceProps

                  (experimental) props used by implementations of BaseDataSource to provide configuration.

                  IExtendedResolverProps

                  (experimental) Additional property for an AppSync resolver for data source reference.

                  IField

                  (experimental) A Graphql Field.

                  IFieldOptions

                  (experimental) Properties for configuring a field.

                  IGraphqlApi

                  (experimental) Interface for GraphQL.

                  IGraphqlApiAttributes

                  (experimental) Attributes for GraphQL imports.

                  IGraphqlApiProps

                  (experimental) Properties for an AppSync GraphQL API.

                  IGraphqlTypeOptions

                  (experimental) Options for GraphQL Types.

                  IHttpDataSourceOptions

                  (experimental) Optional configuration for Http data sources.

                  IHttpDataSourceProps

                  (experimental) Properties for an AppSync http datasource.

                  IIntermediateType

                  (experimental) Intermediate Types are types that includes a certain set of fields that define the entirety of your schema.

                  IIntermediateTypeOptions

                  (experimental) Properties for configuring an Intermediate Type.

                  ILambdaAuthorizerConfig

                  (experimental) Configuration for Lambda authorization in AppSync.

                  ILambdaDataSourceProps

                  (experimental) Properties for an AppSync Lambda datasource.

                  ILogConfig

                  (experimental) Logging configuration for AppSync.

                  INoneDataSourceProps

                  (experimental) Properties for an AppSync dummy datasource.

                  IObjectTypeOptions

                  (experimental) Properties for configuring an Object Type.

                  IOpenIdConnectConfig

                  (experimental) Configuration for OpenID Connect authorization in AppSync.

                  IOpenSearchDataSourceProps

                  (experimental) Properties for the OpenSearch Data Source.

                  IRdsDataSourceProps

                  (experimental) Properties for an AppSync RDS datasource.

                  IResolvableFieldOptions

                  (experimental) Properties for configuring a resolvable field.

                  IResolverProps

                  (experimental) Additional property for an AppSync resolver for GraphQL API reference.

                  ISchemaOptions

                  (experimental) The options for configuring a schema.

                  IUnionTypeOptions

                  (experimental) Properties for configuring an Union Type.

                  IUserPoolConfig

                  (experimental) Configuration for Cognito user-pools in AppSync.

                  Back to top Generated by DocFX