# AWS AppSync Construct Library
<!--BEGIN STABILITY BANNER-->---
![cdk-constructs: Experimental](https://img.shields.io/badge/cdk--constructs-experimental-important.svg?style=for-the-badge)
> The APIs of higher level constructs in this module are experimental and under active development.
> They are subject to non-backward compatible changes or removal in any future version. These are
> not subject to the [Semantic Versioning](https://semver.org/) model and breaking changes will be
> announced in the release notes. This means that while you may use them, you may need to update
> your source code when upgrading to a newer version of this package.
---
<!--END STABILITY BANNER-->
The `@aws-cdk/aws-appsync` package contains constructs for building flexible
APIs that use GraphQL.
```python
import aws_cdk.aws_appsync_alpha as appsync
```
## Example
### DynamoDB
Example of a GraphQL API with `AWS_IAM` [authorization](#authorization) resolving into a DynamoDb
backend data source.
GraphQL schema file `schema.graphql`:
```gql
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`:
```python
api = appsync.GraphqlApi(self, "Api",
name="demo",
schema=appsync.SchemaFile.from_asset(path.join(__dirname, "schema.graphql")),
authorization_config=appsync.AuthorizationConfig(
default_authorization=appsync.AuthorizationMode(
authorization_type=appsync.AuthorizationType.IAM
)
),
xray_enabled=True
)
demo_table = dynamodb.Table(self, "DemoTable",
partition_key=dynamodb.Attribute(
name="id",
type=dynamodb.AttributeType.STRING
)
)
demo_dS = api.add_dynamo_db_data_source("demoDataSource", demo_table)
# Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
# Resolver Mapping Template Reference:
# https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html
demo_dS.create_resolver("QueryGetDemosResolver",
type_name="Query",
field_name="getDemos",
request_mapping_template=appsync.MappingTemplate.dynamo_db_scan_table(),
response_mapping_template=appsync.MappingTemplate.dynamo_db_result_list()
)
# Resolver for the Mutation "addDemo" that puts the item into the DynamoDb table.
demo_dS.create_resolver("MutationAddDemoResolver",
type_name="Mutation",
field_name="addDemo",
request_mapping_template=appsync.MappingTemplate.dynamo_db_put_item(
appsync.PrimaryKey.partition("id").auto(),
appsync.Values.projecting("input")),
response_mapping_template=appsync.MappingTemplate.dynamo_db_result_item()
)
# To enable DynamoDB read consistency with the `MappingTemplate`:
demo_dS.create_resolver("QueryGetDemosConsistentResolver",
type_name="Query",
field_name="getDemosConsistent",
request_mapping_template=appsync.MappingTemplate.dynamo_db_scan_table(True),
response_mapping_template=appsync.MappingTemplate.dynamo_db_result_list()
)
```
### Aurora 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.
```python
# Build a data source for AppSync to access the database.
# api: appsync.GraphqlApi
# Create username and password secret for DB Cluster
secret = rds.DatabaseSecret(self, "AuroraSecret",
username="clusteradmin"
)
# The VPC to place the cluster in
vpc = ec2.Vpc(self, "AuroraVpc")
# Create the serverless cluster, provide all values needed to customise the database.
cluster = rds.ServerlessCluster(self, "AuroraCluster",
engine=rds.DatabaseClusterEngine.AURORA_MYSQL,
vpc=vpc,
credentials={"username": "clusteradmin"},
cluster_identifier="db-endpoint-test",
default_database_name="demos"
)
rds_dS = api.add_rds_data_source("rds", cluster, secret, "demos")
# Set up a resolver for an RDS query.
rds_dS.create_resolver("QueryGetDemosRdsResolver",
type_name="Query",
field_name="getDemosRds",
request_mapping_template=appsync.MappingTemplate.from_string("""
{
"version": "2018-05-29",
"statements": [
"SELECT * FROM demos"
]
}
"""),
response_mapping_template=appsync.MappingTemplate.from_string("""
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
""")
)
# Set up a resolver for an RDS mutation.
rds_dS.create_resolver("MutationAddDemoRdsResolver",
type_name="Mutation",
field_name="addDemoRds",
request_mapping_template=appsync.MappingTemplate.from_string("""
{
"version": "2018-05-29",
"statements": [
"INSERT INTO demos VALUES (:id, :version)",
"SELECT * WHERE id = :id"
],
"variableMap": {
":id": $util.toJson($util.autoId()),
":version": $util.toJson($ctx.args.version)
}
}
"""),
response_mapping_template=appsync.MappingTemplate.from_string("""
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
""")
)
```
### HTTP Endpoints
GraphQL schema file `schema.graphql`:
```gql
type job {
id: String!
version: String!
}
input DemoInput {
version: String!
}
type Mutation {
callStepFunction(input: DemoInput!): job
}
```
GraphQL request mapping template `request.vtl`:
```json
{
"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`:
```json
{
"id": "${context.result.id}"
}
```
CDK stack file `app-stack.ts`:
```python
api = appsync.GraphqlApi(self, "api",
name="api",
schema=appsync.SchemaFile.from_asset(path.join(__dirname, "schema.graphql"))
)
http_ds = api.add_http_data_source("ds", "https://states.amazonaws.com",
name="httpDsWithStepF",
description="from appsync to StepFunctions Workflow",
authorization_config=appsync.AwsIamConfig(
signing_region="us-east-1",
signing_service_name="states"
)
)
http_ds.create_resolver("MutationCallStepFunctionResolver",
type_name="Mutation",
field_name="callStepFunction",
request_mapping_template=appsync.MappingTemplate.from_file("request.vtl"),
response_mapping_template=appsync.MappingTemplate.from_file("response.vtl")
)
```
### Amazon OpenSearch 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.
```python
import aws_cdk.aws_opensearchservice as opensearch
# api: appsync.GraphqlApi
user = iam.User(self, "User")
domain = opensearch.Domain(self, "Domain",
version=opensearch.EngineVersion.OPENSEARCH_1_3,
removal_policy=RemovalPolicy.DESTROY,
fine_grained_access_control=opensearch.AdvancedSecurityOptions(master_user_arn=user.user_arn),
encryption_at_rest=opensearch.EncryptionAtRestOptions(enabled=True),
node_to_node_encryption=True,
enforce_https=True
)
ds = api.add_open_search_data_source("ds", domain)
ds.create_resolver("QueryGetTestsResolver",
type_name="Query",
field_name="getTests",
request_mapping_template=appsync.MappingTemplate.from_string(JSON.stringify({
"version": "2017-02-28",
"operation": "GET",
"path": "/id/post/_search",
"params": {
"headers": {},
"query_string": {},
"body": {"from": 0, "size": 50}
}
})),
response_mapping_template=appsync.MappingTemplate.from_string("""[
#foreach($entry in $context.result.hits.hits)
#if( $velocityCount > 1 ) , #end
$utils.toJson($entry.get("_source"))
#end
]""")
)
```
## Custom Domain 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.
```python
import aws_cdk.aws_certificatemanager as acm
import aws_cdk.aws_route53 as route53
# hosted zone and route53 features
# hosted_zone_id: str
zone_name = "example.com"
my_domain_name = "api.example.com"
certificate = acm.Certificate(self, "cert", domain_name=my_domain_name)
schema = appsync.SchemaFile(file_path="mySchemaFile")
api = appsync.GraphqlApi(self, "api",
name="myApi",
schema=schema,
domain_name=appsync.DomainOptions(
certificate=certificate,
domain_name=my_domain_name
)
)
# hosted zone for adding appsync domain
zone = route53.HostedZone.from_hosted_zone_attributes(self, "HostedZone",
hosted_zone_id=hosted_zone_id,
zone_name=zone_name
)
# create a cname to the appsync domain. will map to something like xxxx.cloudfront.net
route53.CnameRecord(self, "CnameApiRecord",
record_name="api",
zone=zone,
domain_name=api.app_sync_domain_name
)
```
## Log Group
AppSync automatically create a log group with the name `/aws/appsync/apis/<graphql_api_id>` upon deployment with
log data set to never expire. If you want to set a different expiration period, use the `logConfig.retention` property.
To obtain the GraphQL API's log group as a `logs.ILogGroup` use the `logGroup` property of the
`GraphqlApi` construct.
```python
import aws_cdk.aws_logs as logs
log_config = appsync.LogConfig(
retention=logs.RetentionDays.ONE_WEEK
)
appsync.GraphqlApi(self, "api",
authorization_config=appsync.AuthorizationConfig(),
name="myApi",
schema=appsync.SchemaFile.from_asset(path.join(__dirname, "myApi.graphql")),
log_config=log_config
)
```
## Schema
You can define a schema using from a local file using `SchemaFile.fromAsset`
```python
api = appsync.GraphqlApi(self, "api",
name="myApi",
schema=appsync.SchemaFile.from_asset(path.join(__dirname, "schema.graphl"))
)
```
### ISchema
Alternative schema sources can be defined by implementing the `ISchema`
interface. An example of this is the `CodeFirstSchema` class provided in
[awscdk-appsync-utils](https://github.com/cdklabs/awscdk-appsync-utils)
## Imports
Any GraphQL Api that has been created outside the stack can be imported from
another stack into your CDK app. Utilizing the `fromXxx` function, you have
the ability to add data sources and resolvers through a `IGraphqlApi` interface.
```python
# api: appsync.GraphqlApi
# table: dynamodb.Table
imported_api = appsync.GraphqlApi.from_graphql_api_attributes(self, "IApi",
graphql_api_id=api.api_id,
graphql_api_arn=api.arn
)
imported_api.add_dynamo_db_data_source("TableDataSource", table)
```
If you don't 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:
* API Keys (`AuthorizationType.API_KEY`)
* Amazon Cognito User Pools (`AuthorizationType.USER_POOL`)
* OpenID Connect (`AuthorizationType.OPENID_CONNECT`)
* AWS Identity and Access Management (`AuthorizationType.AWS_IAM`)
* AWS Lambda (`AuthorizationType.AWS_LAMBDA`)
These types can be used simultaneously in a single API, allowing different types of clients to
access data. When you specify an authorization type, you can also specify the corresponding
authorization mode to finish defining your authorization. For example, this is a GraphQL API
with AWS Lambda Authorization.
```python
import aws_cdk.aws_lambda as lambda_
# auth_function: lambda.Function
appsync.GraphqlApi(self, "api",
name="api",
schema=appsync.SchemaFile.from_asset(path.join(__dirname, "appsync.test.graphql")),
authorization_config=appsync.AuthorizationConfig(
default_authorization=appsync.AuthorizationMode(
authorization_type=appsync.AuthorizationType.LAMBDA,
lambda_authorizer_config=appsync.LambdaAuthorizerConfig(
handler=auth_function
)
)
)
)
```
## 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`:
```gql
type Mutation {
updateExample(...): ...
@aws_iam
}
```
In `IAM`:
```json
{
"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](https://docs.aws.amazon.com/appsync/latest/devguide/security.html#aws-iam-authorization) for more details.
To make this easier, CDK provides `grant` API.
Use the `grant` function for more granular authorization.
```python
# api: appsync.GraphqlApi
role = iam.Role(self, "Role",
assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
api.grant(role, appsync.IamResource.custom("types/Mutation/fields/updateExample"), "appsync:GraphQL")
```
### IamResource
In order to use the `grant` functions, you need to use the class `IamResource`.
* `IamResource.custom(...arns)` permits custom ARNs and requires an argument.
* `IamResouce.ofType(type, ...fields)` permits ARNs for types and their fields.
* `IamResource.all()` permits ALL resources.
### Generic Permissions
Alternatively, you can use more generic `grant` functions to accomplish the same usage.
These include:
* grantMutation (use to grant access to Mutation fields)
* grantQuery (use to grant access to Query fields)
* grantSubscription (use to grant access to Subscription fields)
```python
# api: appsync.GraphqlApi
# role: iam.Role
# For generic types
api.grant_mutation(role, "updateExample")
# For custom types and granular design
api.grant(role, appsync.IamResource.of_type("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.
```python
# api: appsync.GraphqlApi
appsync_function = appsync.AppsyncFunction(self, "function",
name="appsync_function",
api=api,
data_source=api.add_none_data_source("none"),
request_mapping_template=appsync.MappingTemplate.from_file("request.vtl"),
response_mapping_template=appsync.MappingTemplate.from_file("response.vtl")
)
```
AppSync Functions are used in tandem with pipeline resolvers to compose multiple
operations.
```python
# api: appsync.GraphqlApi
# appsync_function: appsync.AppsyncFunction
pipeline_resolver = appsync.Resolver(self, "pipeline",
api=api,
data_source=api.add_none_data_source("none"),
type_name="typeName",
field_name="fieldName",
request_mapping_template=appsync.MappingTemplate.from_file("beforeRequest.vtl"),
pipeline_config=[appsync_function],
response_mapping_template=appsync.MappingTemplate.from_file("afterResponse.vtl")
)
```
Learn more about Pipeline Resolvers and AppSync Functions [here](https://docs.aws.amazon.com/appsync/latest/devguide/pipeline-resolvers.html).
Raw data
{
"_id": null,
"home_page": "https://github.com/aws/aws-cdk",
"name": "aws-cdk.aws-appsync-alpha",
"maintainer": "",
"docs_url": null,
"requires_python": "~=3.7",
"maintainer_email": "",
"keywords": "",
"author": "Amazon Web Services",
"author_email": "",
"download_url": "https://files.pythonhosted.org/packages/95/fb/68594bd88a22aed241f6c98babfb352388263207d91aaf8bc181055623b6/aws-cdk.aws-appsync-alpha-2.59.0a0.tar.gz",
"platform": null,
"description": "# AWS AppSync Construct Library\n\n<!--BEGIN STABILITY BANNER-->---\n\n\n![cdk-constructs: Experimental](https://img.shields.io/badge/cdk--constructs-experimental-important.svg?style=for-the-badge)\n\n> The APIs of higher level constructs in this module are experimental and under active development.\n> They are subject to non-backward compatible changes or removal in any future version. These are\n> not subject to the [Semantic Versioning](https://semver.org/) model and breaking changes will be\n> announced in the release notes. This means that while you may use them, you may need to update\n> your source code when upgrading to a newer version of this package.\n\n---\n<!--END STABILITY BANNER-->\n\nThe `@aws-cdk/aws-appsync` package contains constructs for building flexible\nAPIs that use GraphQL.\n\n```python\nimport aws_cdk.aws_appsync_alpha as appsync\n```\n\n## Example\n\n### DynamoDB\n\nExample of a GraphQL API with `AWS_IAM` [authorization](#authorization) resolving into a DynamoDb\nbackend data source.\n\nGraphQL schema file `schema.graphql`:\n\n```gql\ntype demo {\n id: String!\n version: String!\n}\ntype Query {\n getDemos: [ demo! ]\n}\ninput DemoInput {\n version: String!\n}\ntype Mutation {\n addDemo(input: DemoInput!): demo\n}\n```\n\nCDK stack file `app-stack.ts`:\n\n```python\napi = appsync.GraphqlApi(self, \"Api\",\n name=\"demo\",\n schema=appsync.SchemaFile.from_asset(path.join(__dirname, \"schema.graphql\")),\n authorization_config=appsync.AuthorizationConfig(\n default_authorization=appsync.AuthorizationMode(\n authorization_type=appsync.AuthorizationType.IAM\n )\n ),\n xray_enabled=True\n)\n\ndemo_table = dynamodb.Table(self, \"DemoTable\",\n partition_key=dynamodb.Attribute(\n name=\"id\",\n type=dynamodb.AttributeType.STRING\n )\n)\n\ndemo_dS = api.add_dynamo_db_data_source(\"demoDataSource\", demo_table)\n\n# Resolver for the Query \"getDemos\" that scans the DynamoDb table and returns the entire list.\n# Resolver Mapping Template Reference:\n# https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html\ndemo_dS.create_resolver(\"QueryGetDemosResolver\",\n type_name=\"Query\",\n field_name=\"getDemos\",\n request_mapping_template=appsync.MappingTemplate.dynamo_db_scan_table(),\n response_mapping_template=appsync.MappingTemplate.dynamo_db_result_list()\n)\n\n# Resolver for the Mutation \"addDemo\" that puts the item into the DynamoDb table.\ndemo_dS.create_resolver(\"MutationAddDemoResolver\",\n type_name=\"Mutation\",\n field_name=\"addDemo\",\n request_mapping_template=appsync.MappingTemplate.dynamo_db_put_item(\n appsync.PrimaryKey.partition(\"id\").auto(),\n appsync.Values.projecting(\"input\")),\n response_mapping_template=appsync.MappingTemplate.dynamo_db_result_item()\n)\n\n# To enable DynamoDB read consistency with the `MappingTemplate`:\ndemo_dS.create_resolver(\"QueryGetDemosConsistentResolver\",\n type_name=\"Query\",\n field_name=\"getDemosConsistent\",\n request_mapping_template=appsync.MappingTemplate.dynamo_db_scan_table(True),\n response_mapping_template=appsync.MappingTemplate.dynamo_db_result_list()\n)\n```\n\n### Aurora Serverless\n\nAppSync provides a data source for executing SQL commands against Amazon Aurora\nServerless clusters. You can use AppSync resolvers to execute SQL statements\nagainst the Data API with GraphQL queries, mutations, and subscriptions.\n\n```python\n# Build a data source for AppSync to access the database.\n# api: appsync.GraphqlApi\n# Create username and password secret for DB Cluster\nsecret = rds.DatabaseSecret(self, \"AuroraSecret\",\n username=\"clusteradmin\"\n)\n\n# The VPC to place the cluster in\nvpc = ec2.Vpc(self, \"AuroraVpc\")\n\n# Create the serverless cluster, provide all values needed to customise the database.\ncluster = rds.ServerlessCluster(self, \"AuroraCluster\",\n engine=rds.DatabaseClusterEngine.AURORA_MYSQL,\n vpc=vpc,\n credentials={\"username\": \"clusteradmin\"},\n cluster_identifier=\"db-endpoint-test\",\n default_database_name=\"demos\"\n)\nrds_dS = api.add_rds_data_source(\"rds\", cluster, secret, \"demos\")\n\n# Set up a resolver for an RDS query.\nrds_dS.create_resolver(\"QueryGetDemosRdsResolver\",\n type_name=\"Query\",\n field_name=\"getDemosRds\",\n request_mapping_template=appsync.MappingTemplate.from_string(\"\"\"\n {\n \"version\": \"2018-05-29\",\n \"statements\": [\n \"SELECT * FROM demos\"\n ]\n }\n \"\"\"),\n response_mapping_template=appsync.MappingTemplate.from_string(\"\"\"\n $utils.toJson($utils.rds.toJsonObject($ctx.result)[0])\n \"\"\")\n)\n\n# Set up a resolver for an RDS mutation.\nrds_dS.create_resolver(\"MutationAddDemoRdsResolver\",\n type_name=\"Mutation\",\n field_name=\"addDemoRds\",\n request_mapping_template=appsync.MappingTemplate.from_string(\"\"\"\n {\n \"version\": \"2018-05-29\",\n \"statements\": [\n \"INSERT INTO demos VALUES (:id, :version)\",\n \"SELECT * WHERE id = :id\"\n ],\n \"variableMap\": {\n \":id\": $util.toJson($util.autoId()),\n \":version\": $util.toJson($ctx.args.version)\n }\n }\n \"\"\"),\n response_mapping_template=appsync.MappingTemplate.from_string(\"\"\"\n $utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])\n \"\"\")\n)\n```\n\n### HTTP Endpoints\n\nGraphQL schema file `schema.graphql`:\n\n```gql\ntype job {\n id: String!\n version: String!\n}\n\ninput DemoInput {\n version: String!\n}\n\ntype Mutation {\n callStepFunction(input: DemoInput!): job\n}\n```\n\nGraphQL request mapping template `request.vtl`:\n\n```json\n{\n \"version\": \"2018-05-29\",\n \"method\": \"POST\",\n \"resourcePath\": \"/\",\n \"params\": {\n \"headers\": {\n \"content-type\": \"application/x-amz-json-1.0\",\n \"x-amz-target\":\"AWSStepFunctions.StartExecution\"\n },\n \"body\": {\n \"stateMachineArn\": \"<your step functions arn>\",\n \"input\": \"{ \\\"id\\\": \\\"$context.arguments.id\\\" }\"\n }\n }\n}\n```\n\nGraphQL response mapping template `response.vtl`:\n\n```json\n{\n \"id\": \"${context.result.id}\"\n}\n```\n\nCDK stack file `app-stack.ts`:\n\n```python\napi = appsync.GraphqlApi(self, \"api\",\n name=\"api\",\n schema=appsync.SchemaFile.from_asset(path.join(__dirname, \"schema.graphql\"))\n)\n\nhttp_ds = api.add_http_data_source(\"ds\", \"https://states.amazonaws.com\",\n name=\"httpDsWithStepF\",\n description=\"from appsync to StepFunctions Workflow\",\n authorization_config=appsync.AwsIamConfig(\n signing_region=\"us-east-1\",\n signing_service_name=\"states\"\n )\n)\n\nhttp_ds.create_resolver(\"MutationCallStepFunctionResolver\",\n type_name=\"Mutation\",\n field_name=\"callStepFunction\",\n request_mapping_template=appsync.MappingTemplate.from_file(\"request.vtl\"),\n response_mapping_template=appsync.MappingTemplate.from_file(\"response.vtl\")\n)\n```\n\n### Amazon OpenSearch Service\n\nAppSync has builtin support for Amazon OpenSearch Service (successor to Amazon\nElasticsearch Service) from domains that are provisioned through your AWS account. You can\nuse AppSync resolvers to perform GraphQL operations such as queries, mutations, and\nsubscriptions.\n\n```python\nimport aws_cdk.aws_opensearchservice as opensearch\n\n# api: appsync.GraphqlApi\n\n\nuser = iam.User(self, \"User\")\ndomain = opensearch.Domain(self, \"Domain\",\n version=opensearch.EngineVersion.OPENSEARCH_1_3,\n removal_policy=RemovalPolicy.DESTROY,\n fine_grained_access_control=opensearch.AdvancedSecurityOptions(master_user_arn=user.user_arn),\n encryption_at_rest=opensearch.EncryptionAtRestOptions(enabled=True),\n node_to_node_encryption=True,\n enforce_https=True\n)\nds = api.add_open_search_data_source(\"ds\", domain)\n\nds.create_resolver(\"QueryGetTestsResolver\",\n type_name=\"Query\",\n field_name=\"getTests\",\n request_mapping_template=appsync.MappingTemplate.from_string(JSON.stringify({\n \"version\": \"2017-02-28\",\n \"operation\": \"GET\",\n \"path\": \"/id/post/_search\",\n \"params\": {\n \"headers\": {},\n \"query_string\": {},\n \"body\": {\"from\": 0, \"size\": 50}\n }\n })),\n response_mapping_template=appsync.MappingTemplate.from_string(\"\"\"[\n #foreach($entry in $context.result.hits.hits)\n #if( $velocityCount > 1 ) , #end\n $utils.toJson($entry.get(\"_source\"))\n #end\n ]\"\"\")\n)\n```\n\n## Custom Domain Names\n\nFor many use cases you may want to associate a custom domain name with your\nGraphQL API. This can be done during the API creation.\n\n```python\nimport aws_cdk.aws_certificatemanager as acm\nimport aws_cdk.aws_route53 as route53\n\n# hosted zone and route53 features\n# hosted_zone_id: str\nzone_name = \"example.com\"\n\n\nmy_domain_name = \"api.example.com\"\ncertificate = acm.Certificate(self, \"cert\", domain_name=my_domain_name)\nschema = appsync.SchemaFile(file_path=\"mySchemaFile\")\napi = appsync.GraphqlApi(self, \"api\",\n name=\"myApi\",\n schema=schema,\n domain_name=appsync.DomainOptions(\n certificate=certificate,\n domain_name=my_domain_name\n )\n)\n\n# hosted zone for adding appsync domain\nzone = route53.HostedZone.from_hosted_zone_attributes(self, \"HostedZone\",\n hosted_zone_id=hosted_zone_id,\n zone_name=zone_name\n)\n\n# create a cname to the appsync domain. will map to something like xxxx.cloudfront.net\nroute53.CnameRecord(self, \"CnameApiRecord\",\n record_name=\"api\",\n zone=zone,\n domain_name=api.app_sync_domain_name\n)\n```\n\n## Log Group\n\nAppSync automatically create a log group with the name `/aws/appsync/apis/<graphql_api_id>` upon deployment with\nlog data set to never expire. If you want to set a different expiration period, use the `logConfig.retention` property.\n\nTo obtain the GraphQL API's log group as a `logs.ILogGroup` use the `logGroup` property of the\n`GraphqlApi` construct.\n\n```python\nimport aws_cdk.aws_logs as logs\n\n\nlog_config = appsync.LogConfig(\n retention=logs.RetentionDays.ONE_WEEK\n)\n\nappsync.GraphqlApi(self, \"api\",\n authorization_config=appsync.AuthorizationConfig(),\n name=\"myApi\",\n schema=appsync.SchemaFile.from_asset(path.join(__dirname, \"myApi.graphql\")),\n log_config=log_config\n)\n```\n\n## Schema\n\nYou can define a schema using from a local file using `SchemaFile.fromAsset`\n\n```python\napi = appsync.GraphqlApi(self, \"api\",\n name=\"myApi\",\n schema=appsync.SchemaFile.from_asset(path.join(__dirname, \"schema.graphl\"))\n)\n```\n\n### ISchema\n\nAlternative schema sources can be defined by implementing the `ISchema`\ninterface. An example of this is the `CodeFirstSchema` class provided in\n[awscdk-appsync-utils](https://github.com/cdklabs/awscdk-appsync-utils)\n\n## Imports\n\nAny GraphQL Api that has been created outside the stack can be imported from\nanother stack into your CDK app. Utilizing the `fromXxx` function, you have\nthe ability to add data sources and resolvers through a `IGraphqlApi` interface.\n\n```python\n# api: appsync.GraphqlApi\n# table: dynamodb.Table\n\nimported_api = appsync.GraphqlApi.from_graphql_api_attributes(self, \"IApi\",\n graphql_api_id=api.api_id,\n graphql_api_arn=api.arn\n)\nimported_api.add_dynamo_db_data_source(\"TableDataSource\", table)\n```\n\nIf you don't specify `graphqlArn` in `fromXxxAttributes`, CDK will autogenerate\nthe expected `arn` for the imported api, given the `apiId`. For creating data\nsources and resolvers, an `apiId` is sufficient.\n\n## Authorization\n\nThere are multiple authorization types available for GraphQL API to cater to different\naccess use cases. They are:\n\n* API Keys (`AuthorizationType.API_KEY`)\n* Amazon Cognito User Pools (`AuthorizationType.USER_POOL`)\n* OpenID Connect (`AuthorizationType.OPENID_CONNECT`)\n* AWS Identity and Access Management (`AuthorizationType.AWS_IAM`)\n* AWS Lambda (`AuthorizationType.AWS_LAMBDA`)\n\nThese types can be used simultaneously in a single API, allowing different types of clients to\naccess data. When you specify an authorization type, you can also specify the corresponding\nauthorization mode to finish defining your authorization. For example, this is a GraphQL API\nwith AWS Lambda Authorization.\n\n```python\nimport aws_cdk.aws_lambda as lambda_\n# auth_function: lambda.Function\n\n\nappsync.GraphqlApi(self, \"api\",\n name=\"api\",\n schema=appsync.SchemaFile.from_asset(path.join(__dirname, \"appsync.test.graphql\")),\n authorization_config=appsync.AuthorizationConfig(\n default_authorization=appsync.AuthorizationMode(\n authorization_type=appsync.AuthorizationType.LAMBDA,\n lambda_authorizer_config=appsync.LambdaAuthorizerConfig(\n handler=auth_function\n )\n )\n )\n)\n```\n\n## Permissions\n\nWhen using `AWS_IAM` as the authorization type for GraphQL API, an IAM Role\nwith correct permissions must be used for access to API.\n\nWhen configuring permissions, you can specify specific resources to only be\naccessible by `IAM` authorization. For example, if you want to only allow mutability\nfor `IAM` authorized access you would configure the following.\n\nIn `schema.graphql`:\n\n```gql\ntype Mutation {\n updateExample(...): ...\n @aws_iam\n}\n```\n\nIn `IAM`:\n\n```json\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"appsync:GraphQL\"\n ],\n \"Resource\": [\n \"arn:aws:appsync:REGION:ACCOUNT_ID:apis/GRAPHQL_ID/types/Mutation/fields/updateExample\"\n ]\n }\n ]\n}\n```\n\nSee [documentation](https://docs.aws.amazon.com/appsync/latest/devguide/security.html#aws-iam-authorization) for more details.\n\nTo make this easier, CDK provides `grant` API.\n\nUse the `grant` function for more granular authorization.\n\n```python\n# api: appsync.GraphqlApi\nrole = iam.Role(self, \"Role\",\n assumed_by=iam.ServicePrincipal(\"lambda.amazonaws.com\")\n)\n\napi.grant(role, appsync.IamResource.custom(\"types/Mutation/fields/updateExample\"), \"appsync:GraphQL\")\n```\n\n### IamResource\n\nIn order to use the `grant` functions, you need to use the class `IamResource`.\n\n* `IamResource.custom(...arns)` permits custom ARNs and requires an argument.\n* `IamResouce.ofType(type, ...fields)` permits ARNs for types and their fields.\n* `IamResource.all()` permits ALL resources.\n\n### Generic Permissions\n\nAlternatively, you can use more generic `grant` functions to accomplish the same usage.\n\nThese include:\n\n* grantMutation (use to grant access to Mutation fields)\n* grantQuery (use to grant access to Query fields)\n* grantSubscription (use to grant access to Subscription fields)\n\n```python\n# api: appsync.GraphqlApi\n# role: iam.Role\n\n\n# For generic types\napi.grant_mutation(role, \"updateExample\")\n\n# For custom types and granular design\napi.grant(role, appsync.IamResource.of_type(\"Mutation\", \"updateExample\"), \"appsync:GraphQL\")\n```\n\n## Pipeline Resolvers and AppSync Functions\n\nAppSync Functions are local functions that perform certain operations onto a\nbackend data source. Developers can compose operations (Functions) and execute\nthem in sequence with Pipeline Resolvers.\n\n```python\n# api: appsync.GraphqlApi\n\n\nappsync_function = appsync.AppsyncFunction(self, \"function\",\n name=\"appsync_function\",\n api=api,\n data_source=api.add_none_data_source(\"none\"),\n request_mapping_template=appsync.MappingTemplate.from_file(\"request.vtl\"),\n response_mapping_template=appsync.MappingTemplate.from_file(\"response.vtl\")\n)\n```\n\nAppSync Functions are used in tandem with pipeline resolvers to compose multiple\noperations.\n\n```python\n# api: appsync.GraphqlApi\n# appsync_function: appsync.AppsyncFunction\n\n\npipeline_resolver = appsync.Resolver(self, \"pipeline\",\n api=api,\n data_source=api.add_none_data_source(\"none\"),\n type_name=\"typeName\",\n field_name=\"fieldName\",\n request_mapping_template=appsync.MappingTemplate.from_file(\"beforeRequest.vtl\"),\n pipeline_config=[appsync_function],\n response_mapping_template=appsync.MappingTemplate.from_file(\"afterResponse.vtl\")\n)\n```\n\nLearn more about Pipeline Resolvers and AppSync Functions [here](https://docs.aws.amazon.com/appsync/latest/devguide/pipeline-resolvers.html).\n\n\n",
"bugtrack_url": null,
"license": "Apache-2.0",
"summary": "The CDK Construct Library for AWS::AppSync",
"version": "2.59.0a0",
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "dc5790222ebb5f393c60fe37589b62d6f9bdac92c63b5aeb0000ef2fa49d9d17",
"md5": "9de85aa929538b4a7b73115d2a26daa7",
"sha256": "ecc235f1f70d404c8d03cf250be0227becd14c468f8c43b6d9df334a1d60c8e2"
},
"downloads": -1,
"filename": "aws_cdk.aws_appsync_alpha-2.59.0a0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "9de85aa929538b4a7b73115d2a26daa7",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "~=3.7",
"size": 223283,
"upload_time": "2023-01-03T17:00:10",
"upload_time_iso_8601": "2023-01-03T17:00:10.096479Z",
"url": "https://files.pythonhosted.org/packages/dc/57/90222ebb5f393c60fe37589b62d6f9bdac92c63b5aeb0000ef2fa49d9d17/aws_cdk.aws_appsync_alpha-2.59.0a0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "95fb68594bd88a22aed241f6c98babfb352388263207d91aaf8bc181055623b6",
"md5": "5efb97423906a5e1ddda0acf18364bd7",
"sha256": "f5c7773b70b759efd576561dc3d71af5762a6f7cbc9ee9eef5e538c7ab3dccc7"
},
"downloads": -1,
"filename": "aws-cdk.aws-appsync-alpha-2.59.0a0.tar.gz",
"has_sig": false,
"md5_digest": "5efb97423906a5e1ddda0acf18364bd7",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "~=3.7",
"size": 224031,
"upload_time": "2023-01-03T17:01:03",
"upload_time_iso_8601": "2023-01-03T17:01:03.464704Z",
"url": "https://files.pythonhosted.org/packages/95/fb/68594bd88a22aed241f6c98babfb352388263207d91aaf8bc181055623b6/aws-cdk.aws-appsync-alpha-2.59.0a0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-01-03 17:01:03",
"github": true,
"gitlab": false,
"bitbucket": false,
"github_user": "aws",
"github_project": "aws-cdk",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "aws-cdk.aws-appsync-alpha"
}