Connect your app code to the API
In this guide, you will connect your application code to the backend API using the Amplify Libraries. We will review how to install and configure Amplify Libraries.
Before you begin, you will need:
- An GraphQL API already set up either via the Amplify CLI, or directly via the underlying AWS AppSync service.
- A frontend application set up. For instructions on setting up an app, see Project Setup: Create your application
- npm installed
Install the Amplify Library
The Amplify Library is the recommended client library used to connect to your GraphQL APIs. To install the the Amplify client library, navigate to your frontend's root folder and run the following command in your Terminal:
npm install aws-amplify
Configure the Amplify Library
You will then configure the library to connect with the Amplify CLI-provisioned API or you existing AppSync GraphQL API:
When you deploy your backend (amplify push
), an amplifyconfiguration.json
file is generated for you. This file contains your API's endpoint information and auth configurations.
import { Amplify } from 'aws-amplify';import config from './amplifyconfiguration.json';
Amplify.configure(config);
To connect your app code to your GraphQL API, you need to provide two configurations:
- the API endpoint URL
- the default authorization mode
Configure the GraphQL API endpoint URL
The Amplify Library connects you to a GraphQL API endpoint based on the information provided to Amplify.configure()
.
When working with existing GraphQL APIs, you must manually provide your API endpoint and auth configurations. First, to configure the GraphQL API endpoint URL, set the endpoint
and region
values.
import { Amplify } from 'aws-amplify';
Amplify.configure({ API: { GraphQL: { // Provide endpoint and region information here endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql', region: 'us-east-1' // Read next section on how to set the correct authorization mode for the API } }});
Next, configure the appropriate authorization mode to authenticate with the API.
Configure the default authorization mode
The Default Authorization Mode is the authorization mode that the GraphQL API should be authorized with when no other authorization mode is specified at the request time.
The Default Authorization Mode is provided as part of the amplifyconfiguration.json if you provisioned your API using the Amplify CLI. If you provisioned your API using other tools, you need to manually set the Default Authorization Mode. Select the default authorization mode from the tabs below to continue:
import { Amplify } from 'aws-amplify';
Amplify.configure({ API: { GraphQL: { endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql', region: 'us-east-1', // Set the default auth mode to "apiKey" and provide the API key value defaultAuthMode: 'apiKey', apiKey: 'da2-xxxxxxxxxxxxxxxxxxxxxxxxxx' } }});
import { Amplify } from 'aws-amplify';
Amplify.configure({ API: { GraphQL: { endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql', region: 'us-east-1', // Set the default auth mode to "userPool" defaultAuthMode: 'userPool' } }});
import { Amplify } from 'aws-amplify';
Amplify.configure({ API: { GraphQL: { endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql', region: 'us-east-1', // Set the default auth mode to "iam" defaultAuthMode: 'iam' } }, Auth: { Cognito: { identityPoolId: "YOUR_IDENTITY_POOL_ID", allowGuestAccess: true // set to false to not use the unauthenticated role } }});
import { Amplify } from 'aws-amplify';
Amplify.configure({ API: { GraphQL: { endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql', region: 'us-east-1', // Set the default auth mode to "OIDC" defaultAuthMode: 'oidc' } }});
Set custom request headers for GraphQL APIs
When working with a GraphQL endpoint, you may need to set request headers for authorization purposes or to pass additional metadata from the client to API. This is done by passing a graphql_headers
function into the configuration:
import { Amplify } from 'aws-amplify';import config from './amplifyconfiguration.json';
Amplify.configure(config, { API: { GraphQL: { headers: async () => ({ 'My-Custom-Header': 'my value' }) } }});
Generate GraphQL client code and typings
You can generate common GraphQL queries, mutations, and subscriptions directly from your backend GraphQL schema. This allows you to avoid hand-authoring GraphQL documents from scratch when developing your API quickly and also provides you end-to-end typing.
By default, when you deploy your API with amplify push
, you're prompted to generate client code for GraphQL queries, mutations, and subscriptions. The generated GraphQL documents are stored in src/graphql/**/
.
amplify push
? Do you want to generate code for your newly created GraphQL API> Yes? Choose the code generation language target> javascript? Enter the file name pattern of graphql queries, mutations and subscriptions> src/graphql/**/*.js? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions> Yes? Enter maximum statement depth [increase from default if your schema is deeply nested]> 2
To customize any of the codegen settings above, run the following command in your Terminal:
amplify update codegen
Go to your frontend app's root directory and run the following command in the Terminal:
npx @aws-amplify/cli codegen add --apiId <...> --region <...>
This will download your API's schema and by default generate client helper code into the src/graphql folder. After every API deployment, you can rerun the following command to generate updated GraphQL statement and types:
npx @aws-amplify/cli codegen
Use generated GraphQL queries, mutations, and subscriptions
You can use the generated GraphQL code after you import them into your codebase and pass them into the client.graphql()
operation. With GraphQL, you typically have the following types of operations to interact with the API from a JavaScript client:
- Mutations - write data to the API (create, update, and delete operations)
import { generateClient } from 'aws-amplify/api';import { createTodo, updateTodo, deleteTodo } from './graphql/mutations';
const client = generateClient();
const todo = { name: 'My first todo', description: 'Hello world!' };
/* create a todo */await client.graphql({ query: createTodo, variables: { input: todo }});
/* update a todo */await client.graphql({ query: updateTodo, variables: { input: { id: 'ENTER_TODO_ID_HERE', name: 'Updated todo info' } }});
/* delete a todo */await client.graphql({ query: deleteTodo, variables: { input: { id: 'ENTER_TODO_ID_HERE' } }});
- Queries - read data from the API (list and get operations)
import { generateClient } from 'aws-amplify/api';import { listTodos } from './graphql/queries';
const client = generateClient();
const todos = await client.graphql({ query: listTodos });
To learn more about queries, mutations, and subscriptions in more detail, see the guides to Create, update, and delete application data and Read application data.
Conclusion
Congratulations! You have finished the Connect your app code to the API guide. In this guide, you reviewed the required configuration and installed and configured Amplify Libraries. You also reviewed some quick ways to write and read this data.
Next steps
Our recommended next steps include using the API to mutate and query data. You can also review how to subscribe to real-time events to look for mutations in your data. Some resources that will help with this work include: