Schema and GraphQL operations
Apollo's code generation plugin reads your schema and GraphQL operation files to generate type-safe Kotlin code. This page covers how to retrieve your AppSync schema and define the GraphQL operations you need.
Retrieve your AWS AppSync GraphQL schema
Using the AWS AppSync web console
- Navigate to your API on the AWS AppSync console
- On the left side, select Schema
- Select the Export Schema dropdown and download the
schema.jsonfile
- Place this file at
app/src/main/graphql/schema.jsonin your project (or the location configured in your Apollo Gradle plugin — see Apollo documentation)
Using the AWS CLI
- Run the following command with the AWS CLI to download the schema:
aws appsync get-introspection-schema \ --api-id <api-id> \ --format JSON \ --region <region> \ schema.jsonYou can find your API ID in the AWS AppSync console or by running:
aws appsync list-graphql-apis --region <region>- Place the downloaded
schema.jsonatapp/src/main/graphql/schema.jsonin your project.
Prepare GraphQL operations (queries, mutations, subscriptions)
Import from Amplify CLI
The Amplify CLI can auto-generate queries (queries.graphql), mutations (mutations.graphql), and subscriptions (subscriptions.graphql) for your Amplify API / AppSync projects. Follow the Client code generation guide to generate these files. Once generated, add them to your project as directed by the Apollo documentation.
Write your own
Place your GraphQL operations in app/src/main/graphql/, which is the default location the Apollo Gradle plugin looks for these files. When writing your own operations, the AWS AppSync Query Editor is helpful for testing.
Fragment
Create a fragment to reuse in all of your operations:
# fragments.graphql
fragment PostDetails on Post { id updatedAt createdAt title content status rating _version _deleted _lastChangedAt}Mutations
Create mutations that modify or create posts. Using the PostDetails fragment returns the same data type in each mutation:
# mutations.graphql
# Createmutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { ... PostDetails }}
# Updatemutation UpdatePost($input: UpdatePostInput!) { updatePost(input: $input) { ... PostDetails }}
# Deletemutation DeletePost($input: DeletePostInput!) { deletePost(input: $input) { id }}Queries
Create queries that fetch PostDetails from AWS AppSync:
# queries.graphql
# Single Itemquery GetPost($id: ID!) { getPost(id: $id) { ... PostDetails }}
# List Itemsquery GetPosts($nextToken: String) { listPosts(nextToken: $nextToken) { items { ... PostDetails } nextToken }}Subscriptions
Create subscriptions that notify the app when a post is created, updated, or deleted:
# subscriptions.graphql
# Createsubscription onCreateSubscription { onCreatePost { ... PostDetails }}
# Updatesubscription onUpdateSubscription { onUpdatePost { ... PostDetails }}
# Deletesubscription onDeleteSubscription { onDeletePost { id }}