From 2520a8242853bddb8f8f7c459f30eb6496d0f145 Mon Sep 17 00:00:00 2001 From: Tyler Roach Date: Wed, 29 Jan 2025 11:47:20 -0500 Subject: [PATCH] Android AppSync Extension Library Documentation Improvements (#8217) Improve Android AppSync Extensions documentation --- .../aws-appsync-apollo-extensions/index.mdx | 411 +++++++++++------- 1 file changed, 260 insertions(+), 151 deletions(-) diff --git a/src/pages/[platform]/build-a-backend/data/aws-appsync-apollo-extensions/index.mdx b/src/pages/[platform]/build-a-backend/data/aws-appsync-apollo-extensions/index.mdx index 53327933062..d12f1f7d0a5 100644 --- a/src/pages/[platform]/build-a-backend/data/aws-appsync-apollo-extensions/index.mdx +++ b/src/pages/[platform]/build-a-backend/data/aws-appsync-apollo-extensions/index.mdx @@ -23,15 +23,13 @@ export function getStaticProps(context) { }; } -AWS AppSync Apollo Extensions provide a seamless way to connect to your AWS AppSync backend using Apollo client, an open-source GraphQL client. - +AWS AppSync Apollo Extensions provide a seamless way to connect to your AWS AppSync backend using Apollo client, an open-source GraphQL client. To learn more about Apollo, see https://www.apollographql.com/docs/ios/. - To learn more about Apollo, see https://www.apollographql.com/docs/kotlin. @@ -42,22 +40,26 @@ To learn more about Apollo, see https://www.apollographql.com/docs/kotlin. AWS AppSync Apollo Extensions provide AWS AppSync authorizers to be used with the Apollo client to make it simple to apply the correct authorization payloads to your GraphQL operations. -The Amplify library provides components to facilitate configuring the authorizers with Apollo client by providing configuration values to connect to your Amplify Data backend. + +Additionally, we publish an optional Amplify extension that allows Amplify to provide auth tokens and signing logic for the corresponding Authorizers. + + + +Additionally, the included Amplify components allow Amplify to provide auth tokens and signing logic for the corresponding Authorizers. + -### Install the AWS AppSync Apollo Extensions library +## Install the AWS AppSync Apollo Extensions library -To connect Apollo to AppSync without using Amplify, add the `apollo-appsync` dependency to your app/build.gradle.kts file. If your -application is using Amplify Android, add the `apollo-appsync-amplify` dependency instead. + + + + +Add the `apollo-appsync-amplify` dependency to your app/build.gradle.kts file. ```kotlin title="app/build.gradle.kts" dependencies { - // highlight-start - // Connect Apollo to AppSync without using Amplify - implementation("com.amplifyframework:apollo-appsync:1.0.0") - // highlight-end - // or // highlight-start // Connect Apollo to AppSync, delegating some implementation details to Amplify implementation("com.amplifyframework:apollo-appsync-amplify:1.0.0") @@ -65,6 +67,24 @@ dependencies { } ``` + + + + +Add the `apollo-appsync` dependency to your app/build.gradle.kts file. + +```kotlin title="app/build.gradle.kts" +dependencies { + // highlight-start + // Connect Apollo to AppSync without using Amplify + implementation("com.amplifyframework:apollo-appsync:1.0.0") + // highlight-end +} +``` + + + + @@ -78,29 +98,71 @@ Enter its GitHub URL (`https://github.com/aws-amplify/aws-appsync-apollo-extensi -### Connecting to AWS AppSync with Apollo client +## Connecting to AWS AppSync with Apollo client -AWS AppSync supports the following [authorization modes](https://docs.aws.amazon.com/appsync/latest/devguide/security-authz.html): + -#### API_KEY +### Creating the ApolloClient - + -```swift -import AWSAppSyncApolloExtensions + +Before you begin, you will need an Amplify Data backend deploy. To get started, see [Set up Data](/[platform]/build-a-backend/data/set-up-data/). -let authorizer = APIKeyAuthorizer(apiKey: "[API_KEY]") -let interceptor = AppSyncInterceptor(authorizer) +Once you have deployed your backend and created the `amplify_outputs.json` file, you can use Amplify library to read and retrieve your configuration values with the following steps: + +```kotlin +// Use apiKey auth mode, reading configuration from AmplifyOutputs +val connector = ApolloAmplifyConnector(context, AmplifyOutputs(R.raw.amplify_outputs)) +val apolloClient = ApolloClient.Builder() + .appSync(connector.endpoint, connector.apiKeyAuthorizer()) + .build() ``` + - + +You can create your Apollo client by using our provided AWS AppSync endpoint and authorizer classes. - +```kotlin +val endpoint = AppSyncEndpoint("") +// Continue Reading to see more authorizer examples +val authorizer = ApiKeyAuthorizer("[API_KEY]") +val apolloClient = ApolloClient.Builder() + .appSync(endpoint, authorizer) + .build() +``` + + + + +### Providing AppSync Authorizers + + + + + +The AWS AppSync Apollo Extensions library provides a number of Authorizer classes to match the various authorization strategies that may be in use in your schema. You should choose the appropriate Authorizer type for your authorization strategy. To read more about the strategies and their corresponding auth modes, see [Available authorization strategies](/[platform]/build-a-backend/data/customize-authz/#available-authorization-strategies). + +Some common ones are + +* `publicAPIkey` strategy, `apiKey` authMode, **APIKeyAuthorizer** +* `guest` strategy, `identityPool` authMode, **IAMAuthorizer** +* `owner` strategy, `userPool` authMode, **AuthTokenAuthorizer** + +If you define multiple authorization strategies within your schema, you will have to create separate Apollo client instances for each Authorizer that you want to use in your app. + +#### API_KEY -An `ApiKeyAuthorizer` can be used with a hardcoded API key, by fetching the key from some source, or reading it from `amplify_outputs.json`: +An `ApiKeyAuthorizer` can read the API key from `amplify_outputs.json`, provide a hardcoded API key, or fetch the API key from some source: ```kotlin // highlight-start +// Using ApolloAmplifyConnector to read API key from amplify_outputs.json +val connector = ApolloAmplifyConnector(context, AmplifyOutputs(R.raw.amplify_outputs)) +val authorizer = connector.apiKeyAuthorizer() +//highlight-end +// or +// highlight-start // Use a hard-coded API key val authorizer = ApiKeyAuthorizer("[API_KEY]") //highlight-end @@ -110,51 +172,10 @@ val authorizer = ApiKeyAuthorizer("[API_KEY]") // so it should implement appropriate caching internally. val authorizer = ApiKeyAuthorizer { fetchApiKey() } //highlight-end -// or -// highlight-start -// Using ApolloAmplifyConnector to read API key from amplify_outputs.json -val connector = ApolloAmplifyConnector(context, AmplifyOutputs(R.raw.amplify_outputs)) -val authorizer = connector.apiKeyAuthorizer() -//highlight-end ``` - - #### AMAZON_COGNITO_USER_POOLS - - -If you are using Amplify Auth, you can create a method that retrieves the Cognito access token - -```swift -import Amplify - -func getUserPoolAccessToken() async throws -> String { - let authSession = try await Amplify.Auth.fetchAuthSession() - if let result = (authSession as? AuthCognitoTokensProvider)?.getCognitoTokens() { - switch result { - case .success(let tokens): - return tokens.accessToken - case .failure(let error): - throw error - } - } - throw AuthError.unknown("Did not receive a valid response from fetchAuthSession for get token.") -} -``` - -Then create the AuthTokenAuthorizer with this method. - -```swift -import AWSAppSyncApolloExtensions - -let authorizer = AuthTokenAuthorizer(fetchLatestAuthToken: getUserPoolAccessToken) -let interceptor = AppSyncInterceptor(authorizer) -``` - - - - You can use `AmplifyApolloConnector` to get an `AuthTokenAuthorizer` instance that supplies the token for the current logged-in Amplify user, or implement the token fetching yourself. ```kotlin @@ -181,30 +202,11 @@ val authorizer = AuthTokenAuthorizer { //highlight-end ``` - - You can provide your own custom `fetchLatestAuthToken` provider for **AWS_LAMBDA** and **OPENID_CONNECT** auth modes. #### AWS_IAM - - -If you are using Amplify Auth, you can use the following method for AWS_IAM auth - -```swift -import AWSCognitoAuthPlugin -import AWSAppSyncApolloExtensions - -let authorizer = IAMAuthorizer( - signRequest: AWSCognitoAuthPlugin.createAppSyncSigner( - region: "[REGION]")) -``` - - - - - -If you are using `apollo-appsync-amplify`, you can use the `ApolloAmplifyConnector` to delegate token fetching and request +You can use the `ApolloAmplifyConnector` to delegate token fetching and request signing to Amplify. ```kotlin @@ -223,15 +225,131 @@ val authorizer = IamAuthorizer { //highlight-end ``` + + + + +AWS AppSync supports the following [authorization modes](https://docs.aws.amazon.com/appsync/latest/devguide/security-authz.html). Use the corresponding Authorizer that matches the chosen authorization type. + +Some common ones are + +* API Key Authorization -> **APIKeyAuthorizer** +* IAM Authorization -> **IAMAuthorizer** +* Cognito User Pools -> **AuthTokenAuthorizer** + +If you apply multiple authorization directives in your schema, you will have to create separate Apollo client instances for each Authorizer that you want to use in your app. + +#### API_KEY + +An `ApiKeyAuthorizer` can be used with a hardcoded API key or by fetching the key from some source.: + +```kotlin +// highlight-start +// Use a hard-coded API key +val authorizer = ApiKeyAuthorizer("[API_KEY]") +//highlight-end +// or +// highlight-start +// Fetch the API key from some source. This function may be called many times, +// so it should implement appropriate caching internally. +val authorizer = ApiKeyAuthorizer { fetchApiKey() } +//highlight-end +``` + +#### AMAZON_COGNITO_USER_POOLS + +When working directly with AppSync, you must implement the token fetching yourself. + +```kotlin +// highlight-start +// Use your own token fetching. This function may be called many times, +// so it should implement appropriate caching internally. +val authorizer = AuthTokenAuthorizer { + fetchLatestAuthToken() +} +//highlight-end +``` + +#### AWS_IAM + +When working directly with AppSync, you must implement the request signing yourself. + +```kotlin +// highlight-start +// Provide an implementation of the signing function. This function should implement the +// AWS Sig-v4 signing logic and return the authorization headers containing the token and signature. +val authorizer = IamAuthorizer { signRequestAndReturnHeaders(it) } +// highlight-end +``` + + + + -### Connecting Amplify Data to Apollo client -Before you begin, you will need an Amplify Data backend deploy. To get started, see [Set up Data](/[platform]/build-a-backend/data/set-up-data/). + +AWS AppSync supports the following [authorization modes](https://docs.aws.amazon.com/appsync/latest/devguide/security-authz.html): -Once you have deployed your backend and created the `amplify_outputs.json` file, you can use Amplify library to read and retrieve your configuration values with the following steps: +### API_KEY + +```swift +import AWSAppSyncApolloExtensions + +let authorizer = APIKeyAuthorizer(apiKey: "[API_KEY]") +let interceptor = AppSyncInterceptor(authorizer) +``` + +### AMAZON_COGNITO_USER_POOLS + +If you are using Amplify Auth, you can create a method that retrieves the Cognito access token + +```swift +import Amplify + +func getUserPoolAccessToken() async throws -> String { + let authSession = try await Amplify.Auth.fetchAuthSession() + if let result = (authSession as? AuthCognitoTokensProvider)?.getCognitoTokens() { + switch result { + case .success(let tokens): + return tokens.accessToken + case .failure(let error): + throw error + } + } + throw AuthError.unknown("Did not receive a valid response from fetchAuthSession for get token.") +} +``` + +Then create the AuthTokenAuthorizer with this method. + +```swift +import AWSAppSyncApolloExtensions + +let authorizer = AuthTokenAuthorizer(fetchLatestAuthToken: getUserPoolAccessToken) +let interceptor = AppSyncInterceptor(authorizer) +``` + +### AWS_IAM + +If you are using Amplify Auth, you can use the following method for AWS_IAM auth + +```swift +import AWSCognitoAuthPlugin +import AWSAppSyncApolloExtensions + +let authorizer = IAMAuthorizer( + signRequest: AWSCognitoAuthPlugin.createAppSyncSigner( + region: "[REGION]")) +``` + +## Connecting Amplify Data to Apollo client + +Before you begin, you will need an Amplify Data backend deploy. To get started, see [Set up Data](/[platform]/build-a-backend/data/set-up-data/). + +Once you have deployed your backend and created the `amplify_outputs.json` file, you can use Amplify library to read and retrieve your configuration values with the following steps: 1. Enter its GitHub URL (`https://github.com/aws-amplify/amplify-swift`), select **Up to Next Major Version** and click **Add Package** 2. Select the following libraries: @@ -266,32 +384,7 @@ func createApolloClient() throws -> ApolloClient { } ``` - - - - -Add `apollo-appsync-amplify` dependency to your app/build.gradle.kts file: - -```kotlin title="app/build.gradle.kts" -dependencies { - // highlight-start - implementation("com.amplifyframework:apollo-appsync-amplify:1.0.0") - // highlight-end -} -``` - -```kotlin -// Use apiKey auth mode, reading configuration from AmplifyOutputs -val connector = ApolloAmplifyConnector(context, AmplifyOutputs(R.raw.amplify_outputs)) -val apolloClient = ApolloClient.Builder() - .appSync(connector.endpoint, connector.apiKeyAuthorizer()) - .build() -``` - - - -Depending on your authorization strategy defined on your schema, you can use the corresponding Authorizer. To read more about the strategies and their corresponding auth modes, see [Available authorization strategies](/[platform]/build-a-backend/data/customize-authz/#available-authorization-strategies). - +The AWS AppSync Apollo Extensions library provides a number of Authorizer classes to match the various authorization strategies that may be in use in your schema. You should choose the appropriate Authorizer type for your authorization strategy. To read more about the strategies and their corresponding auth modes, see [Available authorization strategies](/[platform]/build-a-backend/data/customize-authz/#available-authorization-strategies). Some common ones are @@ -299,16 +392,18 @@ Some common ones are * `guest` strategy, `identityPool` authMode, **IAMAuthorizer** * `owner` strategy, `userPool` authMode, **AuthTokenAuthorizer** -If you define multiple authorization strategies on a single model, you will have to create separate Apollo client instances for each Authorizer that you want to use in your app. +If you define multiple authorization strategies within your schema, you will have to create separate Apollo client instances for each Authorizer that you want to use in your app. + + -### Downloading the AWS AppSync schema +## Downloading the AWS AppSync schema The schema is used by Apollo’s code generation tool to generate API code that helps you execute GraphQL operations. The following steps integrate your AppSync schema with Apollo's code generation process: 1. Navigate to your API on the [AWS AppSync console](https://console.aws.amazon.com/appsync/home) 2. On the left side, select Schema -3. When viewing your schema, there should a “Export schema” drop down. Select this and download the `schema.json` file. +3. Select the "Export schema" dropdown and download the `schema.json` file. 4. Add this file to your project as directed by [Apollo Code Generation documentation](https://www.apollographql.com/docs/ios/code-generation/introduction). You can alternatively download the introspection schema using the [`fetch-schema`](https://www.apollographql.com/docs/ios/code-generation/codegen-cli#fetch-schema) command with the `amplify-ios-cli` tool. @@ -316,12 +411,58 @@ You can alternatively download the introspection schema using the [`fetch-schema + 1. Navigate to your API on the [AWS AppSync console](https://console.aws.amazon.com/appsync/home) 2. On the left side, select Schema -3. When viewing your schema, there should a “Export schema” drop down. Select this and download the `schema.json` file. +3. Select the "Export schema" dropdown and download the `schema.json` file. 4. Add this file to your project as directed by [Apollo documentation](https://www.apollographql.com/docs/kotlin/advanced/plugin-recipes#specifying-the-schema-location) -### Type Mapping AppSync Scalars + + +## Generating Queries, Mutations, and Subscriptions for Apollo client + + + + + + +**Amplify provided .graphql files** +1. Within your Amplify Gen 2 backend, run: `npx ampx generate graphql-client-code --format graphql-codegen --statement-target graphql --out graphql` +2. Copy the generated files (`mutations.graphql`, `queries.graphql`, `subscriptions.graphql`) to your `{app}/src/main/graphql` folder as shown in the [Apollo documentation](https://www.apollographql.com/docs/kotlin#getting-started) + +**Manual** +1. Navigate to the **Queries** tab in your API on the [AWS AppSync console](https://console.aws.amazon.com/appsync/home). Here, you can test queries, mutations, and subscriptions in the GraphQL playground. +2. Enter your GraphQL operation (query, mutation, or subscription) in the editor and select **Run** to execute it. +3. Observe the request and response structure in the results. This gives you insight into the exact call patterns and structure that Apollo will use. +4. Copy the GraphQL operation(s) from the playground and pass them to to your `{app}/src/main/graphql` folder as shown in the [Apollo documentation](https://www.apollographql.com/docs/kotlin#getting-started) + + + + + +1. Navigate to the **Queries** tab in your API on the [AWS AppSync console](https://console.aws.amazon.com/appsync/home). Here, you can test queries, mutations, and subscriptions in the GraphQL playground. +2. Enter your GraphQL operation (query, mutation, or subscription) in the editor and click **Run** to execute it. +3. Observe the request and response structure in the results. This gives you insight into the exact call patterns and structure that Apollo will use. +4. Copy the GraphQL operation from the playground and pass it to Apollo's code generation tool to automatically generate the corresponding API code for your project. + + + + + + + + + +1. Navigate to the **Queries** tab in your API on the [AWS AppSync console](https://console.aws.amazon.com/appsync/home). Here, you can test queries, mutations, and subscriptions in the GraphQL playground. +2. Enter your GraphQL operation (query, mutation, or subscription) in the editor and click **Run** to execute it. +3. Observe the request and response structure in the results. This gives you insight into the exact call patterns and structure that Apollo will use. +4. Copy the GraphQL operation from the playground and pass it to Apollo's code generation tool to automatically generate the corresponding API code for your project. + + + + + +## Type Mapping AppSync Scalars By default, [AWS AppSync Scalars](https://docs.aws.amazon.com/appsync/latest/devguide/scalars.html#graph-ql-aws-appsync-scalars) will default to the `Any` type. You can map these scalars to more explicit types by editing the `apollo` block in your `app/build.gradle[.kts]` file. In the example below, we are now mapping a few of our AppSync scalar types to `String` instead of `Any`. Additional improvements could be made by writing [custom class adapters](https://www.apollographql.com/docs/kotlin/essentials/custom-scalars#define-class-mapping) to convert date/time scalars into Kotlin date/time class types. ```kotlin @@ -335,19 +476,12 @@ apollo { ``` -### Performing Queries, Mutations, and Subscriptions with Apollo client - -1. Navigate to the **Queries** tab in your API on the [AWS AppSync console](https://console.aws.amazon.com/appsync/home). Here, you can test queries, mutations, and subscriptions in the GraphQL playground. -2. Enter your GraphQL operation (query, mutation, or subscription) in the editor and click **Run** to execute it. -3. Observe the request and response structure in the results. This gives you insight into the exact call patterns and structure that Apollo will use. -4. Copy the GraphQL operation from the playground and pass it to Apollo's code generation tool to automatically generate the corresponding API code for your project. + ## Connecting to AWS AppSync real-time endpoint The following example shows how you can create an Apollo client that allows performing GraphQL subscription operations with AWS AppSync. - - ```swift import Apollo import ApolloAPI @@ -384,28 +518,3 @@ func createApolloClient() throws -> ApolloClient { ``` - - - -When using `apollo-appsync`, you create `AppSyncEndpoint` and `AppSyncAuthorizer` instances, and pass them to the ApolloClient's Builder extension function. - -```kotlin -val endpoint = AppSyncEndpoint("") -val authorizer = /* your Authorizer */ - -val apolloClient = ApolloClient.Builder() - .appSync(endpoint, authorizer) - .build() -``` - -When using `apollo-appsync-amplify`, you can get the endpoint and authorizer from an `ApolloAmplifyConnector` to connect to your Amplify backend. - -```kotlin -val connector = ApolloAmplifyConnector(context, AmplifyOutputs(R.raw.amplify_outputs)) - -val apolloClient = ApolloClient.Builder() - .appSync(connector.endpoint, connector.apiKeyAuthorizer()) // or .authTokenAuthorizer(), or .iamAuthorizer() - .build() -``` - -