cdklabs.appsync-utils


Namecdklabs.appsync-utils JSON
Version 0.0.816 PyPI version JSON
download
home_pagehttps://github.com/cdklabs/awscdk-appsync-utils.git
SummaryUtilities for creating appsync apis using aws-cdk
upload_time2025-08-31 00:22:23
maintainerNone
docs_urlNone
authorMitchell Valine<mitchellvaline@yahoo.com>
requires_python~=3.9
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # AWS CDK AppSync Utilities

This package contains various utilities for definining GraphQl Apis via AppSync using the [aws-cdk](https://github.com/aws/aws-cdk).

## Code First Schema Definition

`CodeFirstSchema` 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 files
* **reusability**: removing boilerplate/repetitive code
* **consistency**: resolvers and schema definition will always be synced

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

```python
import { GraphqlApi } from '@aws-cdk/aws-appsync-alpha';
import { CodeFirstSchema } from 'awscdk-appsync-utils';

const schema = new CodeFirstSchema();
const api = new GraphqlApi(this, 'api', { name: 'myApi', schema });

schema.addType(new ObjectType('demo', {
  definition: { id: GraphqlType.id() },
}));
```

### Code-First Example

To showcase the code-first approach. Let's try to model the following schema segment.

```gql
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.

```python
import { GraphqlType, InterfaceType, ObjectType } from 'awscdk-appsync-utils';
const pluralize = require('pluralize');

export const args = {
  after: GraphqlType.string(),
  first: GraphqlType.int(),
  before: GraphqlType.string(),
  last: GraphqlType.int(),
};

export const Node = new InterfaceType('Node', {
  definition: { id: GraphqlType.string() }
});
export const FilmNode = new ObjectType('FilmNode', {
  interfaceTypes: [Node],
  definition: { filmName: GraphqlType.string() }
});

export function generateEdgeAndConnection(base: ObjectType) {
  const edge = new ObjectType(`${base.name}Edge`, {
    definition: { node: base.attribute(), cursor: GraphqlType.string() }
  });
  const connection = new ObjectType(`${base.name}Connection`, {
    definition: {
      edges: edge.attribute({ isList: true }),
      [pluralize(base.name)]: base.attribute({ isList: true }),
      totalCount: GraphqlType.int(),
    }
  });
  return { edge: edge, connection: connection };
}
```

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

```python
declare const dummyRequest: appsync.MappingTemplate;
declare const dummyResponse: appsync.MappingTemplate;

const api = new appsync.GraphqlApi(this, 'Api', {
  name: 'demo',
});

const objectTypes = [ Node, FilmNode ];

const filmConnections = generateEdgeAndConnection(FilmNode);

api.addQuery('allFilms', new ResolvableField({
  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](https://github.com/BryanPan342/starwars-code-first).

## 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:

* [**Scalar Types**](https://docs.aws.amazon.com/appsync/latest/devguide/scalars.html): Id, Int, String, AWSDate, etc.
* [**Object Types**](#Object-Types): types that you generate (i.e. `demo` from the example above)
* [**Interface Types**](#Interface-Types): abstract types that define the base implementation of other
  Intermediate Types

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.
Appsync utils provide static functions to add directives to your CodeFirstSchema.

* `Directive.iam()` sets a type or field's authorization to be validated through `Iam`
* `Directive.apiKey()` sets a type or field's authorization to be validated through a `Api Key`
* `Directive.oidc()` sets a type or field's authorization to be validated through `OpenID Connect`
* `Directive.cognito(...groups: string[])` sets a type or field's authorization to be validated
  through `Cognito User Pools`

  * `groups` the name of the cognito groups to give access

To learn more about authorization and directives, read these docs [here](https://docs.aws.amazon.com/appsync/latest/devguide/security.html).

### 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**](#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:

```gql
type Node {
  test(argument: string): String
}
```

The CDK code required would be:

```python
import { Field, GraphqlType, InterfaceType } from 'awscdk-appsync-utils';

const field = new Field({
  returnType: GraphqlType.string(),
  args: {
    argument: GraphqlType.string(),
  },
});
const type = new InterfaceType('Node', {
  definition: { test: field },
});
```

### Resolvable Fields

`ResolvableField` extends `Field` and will allow you to define arguments and its resolvers.
[**Object Types**](#Object-Types) can have fields that resolve and perform operations on
your backend.

You can also create resolvable fields for object types.

```gql
type Info {
  node(id: String): String
}
```

The CDK code required would be:

```python
declare const api: appsync.GraphqlApi;
declare const dummyRequest: appsync.MappingTemplate;
declare const dummyResponse: appsync.MappingTemplate;

const info = new ObjectType('Info', {
  definition: {
    node: new ResolvableField({
      returnType: GraphqlType.string(),
      args: {
        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:

```gql
type Query {
  get(argument: string): Info
}
```

The CDK code required would be:

```python
declare const api: appsync.GraphqlApi;
declare const dummyRequest: appsync.MappingTemplate;
declare const dummyResponse: appsync.MappingTemplate;

const query = new ObjectType('Query', {
  definition: {
    get: new ResolvableField({
      returnType: GraphqlType.string(),
      args: {
        argument: GraphqlType.string(),
      },
      dataSource: api.addNoneDataSource('none'),
      requestMappingTemplate: dummyRequest,
      responseMappingTemplate: dummyResponse,
    }),
  },
});
```

Learn more about fields and resolvers [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-overview.html).

### 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)
* [**Object Types**](#Object-Types)
* [**Enum Types**](#Enum-Types)
* [**Input Types**](#Input-Types)
* [**Union Types**](#Union-Types)

#### 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***.

```python
const node = new InterfaceType('Node', {
  definition: {
    id: GraphqlType.string({ isRequired: true }),
  },
});
```

To learn more about **Interface Types**, read the docs [here](https://graphql.org/learn/schema/#interfaces).

#### Object Types

**Object Types** are types that you declare. For example, in the [code-first example](#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:

1. Object Types can be created ***externally***.

   ```python
   const schema = new CodeFirstSchema();
   const api = new appsync.GraphqlApi(this, 'Api', {
     name: 'demo',
     schema,
   });
   const demo = new ObjectType('Demo', {
     definition: {
       id: GraphqlType.string({ isRequired: true }),
       version: GraphqlType.string({ isRequired: true }),
     },
   });

   schema.addType(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 definitions

   ```python
   import { ObjectType, GraphqlType } from 'awscdk-appsync-utils';
   export const demo = new ObjectType('Demo', {
     definition: {
       id: GraphqlType.string({ isRequired: true }),
       version: GraphqlType.string({ isRequired: true }),
     },
   });
   ```

   `cdk-stack.ts` - a file containing our cdk stack

   ```python
   declare const schema: CodeFirstSchema;
   schema.addType(demo);
   ```
2. Object Types can be created ***externally*** from an Interface Type.

   ```python
   const node = new InterfaceType('Node', {
     definition: {
       id: GraphqlType.string({ isRequired: true }),
     },
   });
   const demo = new ObjectType('Demo', {
     interfaceTypes: [ node ],
     definition: {
       version: GraphqlType.string({ isRequired: true }),
     },
   });
   ```

   > This method allows for reusability and modularity, ideal for reducing code duplication.

To learn more about **Object Types**, read the docs [here](https://graphql.org/learn/schema/#object-types-and-fields).

#### Enum Types

**Enum Types** are a special type of Intermediate Type. They restrict a particular
set of allowed values for other Intermediate Types.

```gql
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:

```python
declare const api: GraphqlApi;
const episode = new EnumType('Episode', {
  definition: [
    'NEWHOPE',
    'EMPIRE',
    'JEDI',
  ],
});
api.addType(episode);
```

To learn more about **Enum Types**, read the docs [here](https://graphql.org/learn/schema/#enumeration-types).

#### 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.

```gql
input Review {
  stars: Int!
  commentary: String
}
```

The above GraphQL Input Type can be expressed in CDK as the following:

```python
declare const api: appsync.GraphqlApi;
const review = new InputType('Review', {
  definition: {
    stars: GraphqlType.int({ isRequired: true }),
    commentary: GraphqlType.string(),
  },
});
api.addType(review);
```

To learn more about **Input Types**, read the docs [here](https://graphql.org/learn/schema/#input-types).

#### 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.

```gql
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:

```python
declare const api: appsync.GraphqlApi;
const string = GraphqlType.string();
const human = new ObjectType('Human', { definition: { name: string } });
const droid = new ObjectType('Droid', { definition: { name: string } });
const starship = new ObjectType('Starship', { definition: { name: string } }););
const search = new UnionType('Search', {
  definition: [ human, droid, starship ],
});
api.addType(search);
```

To learn more about **Union Types**, read the docs [here](https://graphql.org/learn/schema/#union-types).

### 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.

```python
declare const api: appsync.GraphqlApi;
declare const filmConnection: InterfaceType;
declare const dummyRequest: appsync.MappingTemplate;
declare const dummyResponse: appsync.MappingTemplate;

const string = GraphqlType.string();
const int = GraphqlType.int();
api.addQuery('allFilms', new ResolvableField({
  returnType: filmConnection.attribute(),
  args: { 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](https://docs.aws.amazon.com/appsync/latest/devguide/graphql-overview.html).

### 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.

```python
declare const api: appsync.GraphqlApi;
declare const filmNode: ObjectType;
declare const dummyRequest: appsync.MappingTemplate;
declare const dummyResponse: appsync.MappingTemplate;

const string = GraphqlType.string();
const int = GraphqlType.int();
api.addMutation('addFilm', new ResolvableField({
  returnType: filmNode.attribute(),
  args: { 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](https://docs.aws.amazon.com/appsync/latest/devguide/graphql-overview.html).

### 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.

```python
declare const api: appsync.GraphqlApi;
declare const film: InterfaceType;

api.addSubscription('addedFilm', new Field({
  returnType: film.attribute(),
  args: { id: GraphqlType.id({ isRequired: true }) },
  directives: [Directive.subscribe('addFilm')],
}));
```

To learn more about top level operations, check out the docs [here](https://docs.aws.amazon.com/appsync/latest/devguide/real-time-data.html).

## Merge Source API to Merged API Using A Custom Resource

The SourceApiAssociationMergeOperation construct provides the ability to merge a source api to a Merged Api
and invoke a merge within a Cloudformation custom resource. If the merge operation fails with a conflict, the
Cloudformation update will fail and rollback the changes to the source API in the stack.

```python
import * as cdk from 'aws-cdk-lib';

const sourceApi1ToMerge = new appsync.GraphqlApi(this, 'FirstSourceAPI', {
  name: 'FirstSourceAPI',
  definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.merged-api-1.graphql')),
});

const sourceApi2ToMerge = new appsync.GraphqlApi(this, 'SecondSourceAPI', {
  name: 'SecondSourceAPI',
  definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.merged-api-2.graphql')),
});

const remoteMergedApi = appsync.GraphqlApi.fromGraphqlApiAttributes(this, 'ImportedMergedApi', {
  graphqlApiId: 'MyApiId',
  graphqlApiArn: 'MyApiArn',
});

const remoteExecutionRole = iam.Role.fromRoleArn(this, 'ExecutionRole', 'arn:aws:iam::ACCOUNT:role/MyExistingRole');
const association1 = new appsync.SourceApiAssociation(this, 'SourceApiAssociation1', {
   sourceApi: sourceApi1ToMerge,
   mergedApi: remoteMergedApi,
   mergeType: appsync.MergeType.MANUAL_MERGE,
   mergedApiExecutionRole: remoteExecutionRole,
});

const association2 = new appsync.SourceApiAssociation(this, 'SourceApiAssociation2', {
   sourceApi: sourceApi2ToMerge,
   mergedApi: remoteMergedApi,
   mergeType: appsync.MergeType.MANUAL_MERGE,
   mergedApiExecutionRole: remoteExecutionRole,
});

// The version id can be any identifier defined by the developer. Changing the version identifier allows you to control
// whether a merge operation will take place during deployment.
SourceApiAssociationMergeOperation(this, 'MergeOperation1', {
  sourceApiAssociation: association1,
  versionIdentifier: '1',
});

// Optionally, you can add the alwaysMergeOnStackUpdate flag instead which will ensure that the merge operation occurs
// during every stack update, regardless if there was a change or not. Note that this may lead to merge operations that
//do not actually change the MergedAPI.
SourceApiAssociationMergeOperation(this, 'MergeOperation2', {
  sourceApiAssociation: association2,
  alwaysMergeOnStackUpdate: true,
});
```

## Contributing

This library leans towards high level and experimental features for appsync cdk users. If you have an idea for additional utilities please create an issue describing the feature.

See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.

## License

This project is licensed under the Apache-2.0 License.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/cdklabs/awscdk-appsync-utils.git",
    "name": "cdklabs.appsync-utils",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "~=3.9",
    "maintainer_email": null,
    "keywords": null,
    "author": "Mitchell Valine<mitchellvaline@yahoo.com>",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/7e/e6/0cdccd74cb40d1ebe8eb8fb221f3def90a2076d530b18deccee984f1e79b/cdklabs_appsync_utils-0.0.816.tar.gz",
    "platform": null,
    "description": "# AWS CDK AppSync Utilities\n\nThis package contains various utilities for definining GraphQl Apis via AppSync using the [aws-cdk](https://github.com/aws/aws-cdk).\n\n## Code First Schema Definition\n\n`CodeFirstSchema` offers the ability to generate your schema in a code-first\napproach. A code-first approach offers a developer workflow with:\n\n* **modularity**: organizing schema type definitions into different files\n* **reusability**: removing boilerplate/repetitive code\n* **consistency**: resolvers and schema definition will always be synced\n\nThe code-first approach allows for **dynamic** schema generation. You can\ngenerate your schema based on variables and templates to reduce code\nduplication.\n\n```python\nimport { GraphqlApi } from '@aws-cdk/aws-appsync-alpha';\nimport { CodeFirstSchema } from 'awscdk-appsync-utils';\n\nconst schema = new CodeFirstSchema();\nconst api = new GraphqlApi(this, 'api', { name: 'myApi', schema });\n\nschema.addType(new ObjectType('demo', {\n  definition: { id: GraphqlType.id() },\n}));\n```\n\n### Code-First Example\n\nTo showcase the code-first approach. Let's try to model the following schema segment.\n\n```gql\ninterface Node {\n  id: String\n}\n\ntype Query {\n  allFilms(after: String, first: Int, before: String, last: Int): FilmConnection\n}\n\ntype FilmNode implements Node {\n  filmName: String\n}\n\ntype FilmConnection {\n  edges: [FilmEdge]\n  films: [Film]\n  totalCount: Int\n}\n\ntype FilmEdge {\n  node: Film\n  cursor: String\n}\n```\n\nAbove we see a schema that allows for generating paginated responses. For example,\nwe can query `allFilms(first: 100)` since `FilmConnection` acts as an intermediary\nfor holding `FilmEdges` we can write a resolver to return the first 100 films.\n\nIn a separate file, we can declare our object types and related functions.\nWe will call this file `object-types.ts` and we will have created it in a way that\nallows us to generate other `XxxConnection` and `XxxEdges` in the future.\n\n```python\nimport { GraphqlType, InterfaceType, ObjectType } from 'awscdk-appsync-utils';\nconst pluralize = require('pluralize');\n\nexport const args = {\n  after: GraphqlType.string(),\n  first: GraphqlType.int(),\n  before: GraphqlType.string(),\n  last: GraphqlType.int(),\n};\n\nexport const Node = new InterfaceType('Node', {\n  definition: { id: GraphqlType.string() }\n});\nexport const FilmNode = new ObjectType('FilmNode', {\n  interfaceTypes: [Node],\n  definition: { filmName: GraphqlType.string() }\n});\n\nexport function generateEdgeAndConnection(base: ObjectType) {\n  const edge = new ObjectType(`${base.name}Edge`, {\n    definition: { node: base.attribute(), cursor: GraphqlType.string() }\n  });\n  const connection = new ObjectType(`${base.name}Connection`, {\n    definition: {\n      edges: edge.attribute({ isList: true }),\n      [pluralize(base.name)]: base.attribute({ isList: true }),\n      totalCount: GraphqlType.int(),\n    }\n  });\n  return { edge: edge, connection: connection };\n}\n```\n\nFinally, we will go to our `cdk-stack` and combine everything together\nto generate our schema.\n\n```python\ndeclare const dummyRequest: appsync.MappingTemplate;\ndeclare const dummyResponse: appsync.MappingTemplate;\n\nconst api = new appsync.GraphqlApi(this, 'Api', {\n  name: 'demo',\n});\n\nconst objectTypes = [ Node, FilmNode ];\n\nconst filmConnections = generateEdgeAndConnection(FilmNode);\n\napi.addQuery('allFilms', new ResolvableField({\n  returnType: filmConnections.connection.attribute(),\n  args: args,\n  dataSource: api.addNoneDataSource('none'),\n  requestMappingTemplate: dummyRequest,\n  responseMappingTemplate: dummyResponse,\n}));\n\napi.addType(Node);\napi.addType(FilmNode);\napi.addType(filmConnections.edge);\napi.addType(filmConnections.connection);\n```\n\nNotice how we can utilize the `generateEdgeAndConnection` function to generate\nObject Types. In the future, if we wanted to create more Object Types, we can simply\ncreate the base Object Type (i.e. Film) and from there we can generate its respective\n`Connections` and `Edges`.\n\nCheck out a more in-depth example [here](https://github.com/BryanPan342/starwars-code-first).\n\n## GraphQL Types\n\nOne of the benefits of GraphQL is its strongly typed nature. We define the\ntypes within an object, query, mutation, interface, etc. as **GraphQL Types**.\n\nGraphQL Types are the building blocks of types, whether they are scalar, objects,\ninterfaces, etc. GraphQL Types can be:\n\n* [**Scalar Types**](https://docs.aws.amazon.com/appsync/latest/devguide/scalars.html): Id, Int, String, AWSDate, etc.\n* [**Object Types**](#Object-Types): types that you generate (i.e. `demo` from the example above)\n* [**Interface Types**](#Interface-Types): abstract types that define the base implementation of other\n  Intermediate Types\n\nMore concretely, GraphQL Types are simply the types appended to variables.\nReferencing the object type `Demo` in the previous example, the GraphQL Types\nis `String!` and is applied to both the names `id` and `version`.\n\n### Directives\n\n`Directives` are attached to a field or type and affect the execution of queries,\nmutations, and types. With AppSync, we use `Directives` to configure authorization.\nAppsync utils provide static functions to add directives to your CodeFirstSchema.\n\n* `Directive.iam()` sets a type or field's authorization to be validated through `Iam`\n* `Directive.apiKey()` sets a type or field's authorization to be validated through a `Api Key`\n* `Directive.oidc()` sets a type or field's authorization to be validated through `OpenID Connect`\n* `Directive.cognito(...groups: string[])` sets a type or field's authorization to be validated\n  through `Cognito User Pools`\n\n  * `groups` the name of the cognito groups to give access\n\nTo learn more about authorization and directives, read these docs [here](https://docs.aws.amazon.com/appsync/latest/devguide/security.html).\n\n### Field and Resolvable Fields\n\nWhile `GraphqlType` is a base implementation for GraphQL fields, we have abstractions\non top of `GraphqlType` that provide finer grain support.\n\n### Field\n\n`Field` extends `GraphqlType` and will allow you to define arguments. [**Interface Types**](#Interface-Types) are not resolvable and this class will allow you to define arguments,\nbut not its resolvers.\n\nFor example, if we want to create the following type:\n\n```gql\ntype Node {\n  test(argument: string): String\n}\n```\n\nThe CDK code required would be:\n\n```python\nimport { Field, GraphqlType, InterfaceType } from 'awscdk-appsync-utils';\n\nconst field = new Field({\n  returnType: GraphqlType.string(),\n  args: {\n    argument: GraphqlType.string(),\n  },\n});\nconst type = new InterfaceType('Node', {\n  definition: { test: field },\n});\n```\n\n### Resolvable Fields\n\n`ResolvableField` extends `Field` and will allow you to define arguments and its resolvers.\n[**Object Types**](#Object-Types) can have fields that resolve and perform operations on\nyour backend.\n\nYou can also create resolvable fields for object types.\n\n```gql\ntype Info {\n  node(id: String): String\n}\n```\n\nThe CDK code required would be:\n\n```python\ndeclare const api: appsync.GraphqlApi;\ndeclare const dummyRequest: appsync.MappingTemplate;\ndeclare const dummyResponse: appsync.MappingTemplate;\n\nconst info = new ObjectType('Info', {\n  definition: {\n    node: new ResolvableField({\n      returnType: GraphqlType.string(),\n      args: {\n        id: GraphqlType.string(),\n      },\n      dataSource: api.addNoneDataSource('none'),\n      requestMappingTemplate: dummyRequest,\n      responseMappingTemplate: dummyResponse,\n    }),\n  },\n});\n```\n\nTo nest resolvers, we can also create top level query types that call upon\nother types. Building off the previous example, if we want the following graphql\ntype definition:\n\n```gql\ntype Query {\n  get(argument: string): Info\n}\n```\n\nThe CDK code required would be:\n\n```python\ndeclare const api: appsync.GraphqlApi;\ndeclare const dummyRequest: appsync.MappingTemplate;\ndeclare const dummyResponse: appsync.MappingTemplate;\n\nconst query = new ObjectType('Query', {\n  definition: {\n    get: new ResolvableField({\n      returnType: GraphqlType.string(),\n      args: {\n        argument: GraphqlType.string(),\n      },\n      dataSource: api.addNoneDataSource('none'),\n      requestMappingTemplate: dummyRequest,\n      responseMappingTemplate: dummyResponse,\n    }),\n  },\n});\n```\n\nLearn more about fields and resolvers [here](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-overview.html).\n\n### Intermediate Types\n\nIntermediate Types are defined by Graphql Types and Fields. They have a set of defined\nfields, where each field corresponds to another type in the system. Intermediate\nTypes will be the meat of your GraphQL Schema as they are the types defined by you.\n\nIntermediate Types include:\n\n* [**Interface Types**](#Interface-Types)\n* [**Object Types**](#Object-Types)\n* [**Enum Types**](#Enum-Types)\n* [**Input Types**](#Input-Types)\n* [**Union Types**](#Union-Types)\n\n#### Interface Types\n\n**Interface Types** are abstract types that define the implementation of other\nintermediate types. They are useful for eliminating duplication and can be used\nto generate Object Types with less work.\n\nYou can create Interface Types ***externally***.\n\n```python\nconst node = new InterfaceType('Node', {\n  definition: {\n    id: GraphqlType.string({ isRequired: true }),\n  },\n});\n```\n\nTo learn more about **Interface Types**, read the docs [here](https://graphql.org/learn/schema/#interfaces).\n\n#### Object Types\n\n**Object Types** are types that you declare. For example, in the [code-first example](#code-first-example)\nthe `demo` variable is an **Object Type**. **Object Types** are defined by\nGraphQL Types and are only usable when linked to a GraphQL Api.\n\nYou can create Object Types in two ways:\n\n1. Object Types can be created ***externally***.\n\n   ```python\n   const schema = new CodeFirstSchema();\n   const api = new appsync.GraphqlApi(this, 'Api', {\n     name: 'demo',\n     schema,\n   });\n   const demo = new ObjectType('Demo', {\n     definition: {\n       id: GraphqlType.string({ isRequired: true }),\n       version: GraphqlType.string({ isRequired: true }),\n     },\n   });\n\n   schema.addType(demo);\n   ```\n\n   > This method allows for reusability and modularity, ideal for larger projects.\n   > For example, imagine moving all Object Type definition outside the stack.\n\n   `object-types.ts` - a file for object type definitions\n\n   ```python\n   import { ObjectType, GraphqlType } from 'awscdk-appsync-utils';\n   export const demo = new ObjectType('Demo', {\n     definition: {\n       id: GraphqlType.string({ isRequired: true }),\n       version: GraphqlType.string({ isRequired: true }),\n     },\n   });\n   ```\n\n   `cdk-stack.ts` - a file containing our cdk stack\n\n   ```python\n   declare const schema: CodeFirstSchema;\n   schema.addType(demo);\n   ```\n2. Object Types can be created ***externally*** from an Interface Type.\n\n   ```python\n   const node = new InterfaceType('Node', {\n     definition: {\n       id: GraphqlType.string({ isRequired: true }),\n     },\n   });\n   const demo = new ObjectType('Demo', {\n     interfaceTypes: [ node ],\n     definition: {\n       version: GraphqlType.string({ isRequired: true }),\n     },\n   });\n   ```\n\n   > This method allows for reusability and modularity, ideal for reducing code duplication.\n\nTo learn more about **Object Types**, read the docs [here](https://graphql.org/learn/schema/#object-types-and-fields).\n\n#### Enum Types\n\n**Enum Types** are a special type of Intermediate Type. They restrict a particular\nset of allowed values for other Intermediate Types.\n\n```gql\nenum Episode {\n  NEWHOPE\n  EMPIRE\n  JEDI\n}\n```\n\n> This means that wherever we use the type Episode in our schema, we expect it to\n> be exactly one of NEWHOPE, EMPIRE, or JEDI.\n\nThe above GraphQL Enumeration Type can be expressed in CDK as the following:\n\n```python\ndeclare const api: GraphqlApi;\nconst episode = new EnumType('Episode', {\n  definition: [\n    'NEWHOPE',\n    'EMPIRE',\n    'JEDI',\n  ],\n});\napi.addType(episode);\n```\n\nTo learn more about **Enum Types**, read the docs [here](https://graphql.org/learn/schema/#enumeration-types).\n\n#### Input Types\n\n**Input Types** are special types of Intermediate Types. They give users an\neasy way to pass complex objects for top level Mutation and Queries.\n\n```gql\ninput Review {\n  stars: Int!\n  commentary: String\n}\n```\n\nThe above GraphQL Input Type can be expressed in CDK as the following:\n\n```python\ndeclare const api: appsync.GraphqlApi;\nconst review = new InputType('Review', {\n  definition: {\n    stars: GraphqlType.int({ isRequired: true }),\n    commentary: GraphqlType.string(),\n  },\n});\napi.addType(review);\n```\n\nTo learn more about **Input Types**, read the docs [here](https://graphql.org/learn/schema/#input-types).\n\n#### Union Types\n\n**Union Types** are a special type of Intermediate Type. They are similar to\nInterface Types, but they cannot specify any common fields between types.\n\n**Note:** the fields of a union type need to be `Object Types`. In other words, you\ncan't create a union type out of interfaces, other unions, or inputs.\n\n```gql\nunion Search = Human | Droid | Starship\n```\n\nThe above GraphQL Union Type encompasses the Object Types of Human, Droid and Starship. It\ncan be expressed in CDK as the following:\n\n```python\ndeclare const api: appsync.GraphqlApi;\nconst string = GraphqlType.string();\nconst human = new ObjectType('Human', { definition: { name: string } });\nconst droid = new ObjectType('Droid', { definition: { name: string } });\nconst starship = new ObjectType('Starship', { definition: { name: string } }););\nconst search = new UnionType('Search', {\n  definition: [ human, droid, starship ],\n});\napi.addType(search);\n```\n\nTo learn more about **Union Types**, read the docs [here](https://graphql.org/learn/schema/#union-types).\n\n### Query\n\nEvery schema requires a top level Query type. By default, the schema will look\nfor the `Object Type` named `Query`. The top level `Query` is the **only** exposed\ntype that users can access to perform `GET` operations on your Api.\n\nTo add fields for these queries, we can simply run the `addQuery` function to add\nto the schema's `Query` type.\n\n```python\ndeclare const api: appsync.GraphqlApi;\ndeclare const filmConnection: InterfaceType;\ndeclare const dummyRequest: appsync.MappingTemplate;\ndeclare const dummyResponse: appsync.MappingTemplate;\n\nconst string = GraphqlType.string();\nconst int = GraphqlType.int();\napi.addQuery('allFilms', new ResolvableField({\n  returnType: filmConnection.attribute(),\n  args: { after: string, first: int, before: string, last: int},\n  dataSource: api.addNoneDataSource('none'),\n  requestMappingTemplate: dummyRequest,\n  responseMappingTemplate: dummyResponse,\n}));\n```\n\nTo learn more about top level operations, check out the docs [here](https://docs.aws.amazon.com/appsync/latest/devguide/graphql-overview.html).\n\n### Mutation\n\nEvery schema **can** have a top level Mutation type. By default, the schema will look\nfor the `ObjectType` named `Mutation`. The top level `Mutation` Type is the only exposed\ntype that users can access to perform `mutable` operations on your Api.\n\nTo add fields for these mutations, we can simply run the `addMutation` function to add\nto the schema's `Mutation` type.\n\n```python\ndeclare const api: appsync.GraphqlApi;\ndeclare const filmNode: ObjectType;\ndeclare const dummyRequest: appsync.MappingTemplate;\ndeclare const dummyResponse: appsync.MappingTemplate;\n\nconst string = GraphqlType.string();\nconst int = GraphqlType.int();\napi.addMutation('addFilm', new ResolvableField({\n  returnType: filmNode.attribute(),\n  args: { name: string, film_number: int },\n  dataSource: api.addNoneDataSource('none'),\n  requestMappingTemplate: dummyRequest,\n  responseMappingTemplate: dummyResponse,\n}));\n```\n\nTo learn more about top level operations, check out the docs [here](https://docs.aws.amazon.com/appsync/latest/devguide/graphql-overview.html).\n\n### Subscription\n\nEvery schema **can** have a top level Subscription type. The top level `Subscription` Type\nis the only exposed type that users can access to invoke a response to a mutation. `Subscriptions`\nnotify users when a mutation specific mutation is called. This means you can make any data source\nreal time by specify a GraphQL Schema directive on a mutation.\n\n**Note**: The AWS AppSync client SDK automatically handles subscription connection management.\n\nTo add fields for these subscriptions, we can simply run the `addSubscription` function to add\nto the schema's `Subscription` type.\n\n```python\ndeclare const api: appsync.GraphqlApi;\ndeclare const film: InterfaceType;\n\napi.addSubscription('addedFilm', new Field({\n  returnType: film.attribute(),\n  args: { id: GraphqlType.id({ isRequired: true }) },\n  directives: [Directive.subscribe('addFilm')],\n}));\n```\n\nTo learn more about top level operations, check out the docs [here](https://docs.aws.amazon.com/appsync/latest/devguide/real-time-data.html).\n\n## Merge Source API to Merged API Using A Custom Resource\n\nThe SourceApiAssociationMergeOperation construct provides the ability to merge a source api to a Merged Api\nand invoke a merge within a Cloudformation custom resource. If the merge operation fails with a conflict, the\nCloudformation update will fail and rollback the changes to the source API in the stack.\n\n```python\nimport * as cdk from 'aws-cdk-lib';\n\nconst sourceApi1ToMerge = new appsync.GraphqlApi(this, 'FirstSourceAPI', {\n  name: 'FirstSourceAPI',\n  definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.merged-api-1.graphql')),\n});\n\nconst sourceApi2ToMerge = new appsync.GraphqlApi(this, 'SecondSourceAPI', {\n  name: 'SecondSourceAPI',\n  definition: appsync.Definition.fromFile(path.join(__dirname, 'appsync.merged-api-2.graphql')),\n});\n\nconst remoteMergedApi = appsync.GraphqlApi.fromGraphqlApiAttributes(this, 'ImportedMergedApi', {\n  graphqlApiId: 'MyApiId',\n  graphqlApiArn: 'MyApiArn',\n});\n\nconst remoteExecutionRole = iam.Role.fromRoleArn(this, 'ExecutionRole', 'arn:aws:iam::ACCOUNT:role/MyExistingRole');\nconst association1 = new appsync.SourceApiAssociation(this, 'SourceApiAssociation1', {\n   sourceApi: sourceApi1ToMerge,\n   mergedApi: remoteMergedApi,\n   mergeType: appsync.MergeType.MANUAL_MERGE,\n   mergedApiExecutionRole: remoteExecutionRole,\n});\n\nconst association2 = new appsync.SourceApiAssociation(this, 'SourceApiAssociation2', {\n   sourceApi: sourceApi2ToMerge,\n   mergedApi: remoteMergedApi,\n   mergeType: appsync.MergeType.MANUAL_MERGE,\n   mergedApiExecutionRole: remoteExecutionRole,\n});\n\n// The version id can be any identifier defined by the developer. Changing the version identifier allows you to control\n// whether a merge operation will take place during deployment.\nSourceApiAssociationMergeOperation(this, 'MergeOperation1', {\n  sourceApiAssociation: association1,\n  versionIdentifier: '1',\n});\n\n// Optionally, you can add the alwaysMergeOnStackUpdate flag instead which will ensure that the merge operation occurs\n// during every stack update, regardless if there was a change or not. Note that this may lead to merge operations that\n//do not actually change the MergedAPI.\nSourceApiAssociationMergeOperation(this, 'MergeOperation2', {\n  sourceApiAssociation: association2,\n  alwaysMergeOnStackUpdate: true,\n});\n```\n\n## Contributing\n\nThis library leans towards high level and experimental features for appsync cdk users. If you have an idea for additional utilities please create an issue describing the feature.\n\nSee [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.\n\n## License\n\nThis project is licensed under the Apache-2.0 License.\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "Utilities for creating appsync apis using aws-cdk",
    "version": "0.0.816",
    "project_urls": {
        "Homepage": "https://github.com/cdklabs/awscdk-appsync-utils.git",
        "Source": "https://github.com/cdklabs/awscdk-appsync-utils.git"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "08f1345ac5bf2af8fae2f0e7c670205d7e8654abad164ff831df6e08be3cc6a7",
                "md5": "3643b570e0491eaac344bc55c773c373",
                "sha256": "c8b2866d12d3d36c8327547302d98ec8cb28fceafff6b39d199a7ad454a1a390"
            },
            "downloads": -1,
            "filename": "cdklabs_appsync_utils-0.0.816-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "3643b570e0491eaac344bc55c773c373",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "~=3.9",
            "size": 132894,
            "upload_time": "2025-08-31T00:22:21",
            "upload_time_iso_8601": "2025-08-31T00:22:21.156384Z",
            "url": "https://files.pythonhosted.org/packages/08/f1/345ac5bf2af8fae2f0e7c670205d7e8654abad164ff831df6e08be3cc6a7/cdklabs_appsync_utils-0.0.816-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "7ee60cdccd74cb40d1ebe8eb8fb221f3def90a2076d530b18deccee984f1e79b",
                "md5": "419ec1ac8abd895dd9562c88fe58889a",
                "sha256": "d72aed34bc6f73ff2250a725fae61802c086412ba389b6d6b2e6f385558d8e1b"
            },
            "downloads": -1,
            "filename": "cdklabs_appsync_utils-0.0.816.tar.gz",
            "has_sig": false,
            "md5_digest": "419ec1ac8abd895dd9562c88fe58889a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "~=3.9",
            "size": 139772,
            "upload_time": "2025-08-31T00:22:23",
            "upload_time_iso_8601": "2025-08-31T00:22:23.058734Z",
            "url": "https://files.pythonhosted.org/packages/7e/e6/0cdccd74cb40d1ebe8eb8fb221f3def90a2076d530b18deccee984f1e79b/cdklabs_appsync_utils-0.0.816.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-31 00:22:23",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "cdklabs",
    "github_project": "awscdk-appsync-utils",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "cdklabs.appsync-utils"
}
        
Elapsed time: 0.57804s