Page updated Mar 20, 2024

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:

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:

1npm install aws-amplify@^5

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 aws-exports.js file is generated for you. This file contains your API's endpoint information and auth configurations.

1import { Amplify } from 'aws-amplify'
2import awsconfig from './aws-exports'
3
4Amplify.configure(awsconfig)

To connect your app code to your GraphQL API, you need to provide two configurations:

  1. the API endpoint URL
  2. 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 aws_appsync_graphqlEndpoint and aws_appsync_region values.

1import { Amplify } from 'aws-amplify'
2
3Amplify.configure({
4 aws_appsync_graphqlEndpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
5 aws_appsync_region: 'us-east-1',
6})

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. Default Authorization Mode is a setting that you can configure for the AWS Amplify-generated APIs and AWS AppSync GraphQL APIs. Select the default authorization mode from the tabs below to continue:

1import { Amplify } from 'aws-amplify'
2
3Amplify.configure({
4 aws_appsync_graphqlEndpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
5 aws_appsync_region: 'us-east-1',
6
7 // Set the auth type as "API_KEY" and pass in the API key value
8 aws_appsync_authenticationType: 'API_KEY',
9 aws_appsync_apiKey: 'da2-xxxxxxxxxxxxxxxxxxxxxxxxxx'
10})
1import { Amplify } from 'aws-amplify'
2
3Amplify.configure({
4 aws_appsync_graphqlEndpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
5 aws_appsync_region: 'us-east-1',
6
7 // Set the auth type as "AMAZON_COGNITO_USER_POOLS"
8 aws_appsync_authenticationType: 'AMAZON_COGNITO_USER_POOLS',
9})
1import { Amplify } from 'aws-amplify'
2
3Amplify.configure({
4 aws_appsync_graphqlEndpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
5 aws_appsync_region: 'us-east-1',
6
7 // Set the auth type as "AWS_IAM"
8 aws_appsync_authenticationType: 'AWS_IAM',
9})
1import { Amplify } from 'aws-amplify'
2
3Amplify.configure({
4 aws_appsync_graphqlEndpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
5 aws_appsync_region: 'us-east-1',
6
7 // Set the auth type as "OPENID_CONNECT"
8 aws_appsync_authenticationType: 'OPENID_CONNECT',
9})

You can implement your own custom API authorization logic using an AWS Lambda function. To add a Lambda as an authorization mode for your AppSync API, go to the Settings section of the AppSync console.

If you are using a Lambda function as an authorization mode with your AppSync API, you will need to pass an authentication token with each API request and will need to manage token refresh in your application.

1import { Amplify } from 'aws-amplify'
2
3Amplify.configure({
4 aws_appsync_graphqlEndpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
5 aws_appsync_region: 'us-east-1',
6
7 // Set the auth type as "AWS_LAMBDA"
8 aws_appsync_authenticationType: 'AWS_LAMBDA',
9})

Next, when you make the GraphQL API request, you can provide an authToken parameter to add to your request header.

1const getAuthToken = () => 'myAuthToken';
2const lambdaAuthToken = getAuthToken();
3
4const createdTodo = await client.graphql({
5 query: queries.listTodos,
6 authToken: lambdaAuthToken
7});

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

1amplify push
1? Do you want to generate code for your newly created GraphQL API
2> Yes
3? Choose the code generation language target
4> javascript
5? Enter the file name pattern of graphql queries, mutations and subscriptions
6> src/graphql/**/*.js
7? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions
8> Yes
9? Enter maximum statement depth [increase from default if your schema is deeply nested]
10> 2

To customize any of the codegen settings above, run the following command in your Terminal:

1amplify update codegen

Go to your frontend app's root directory and run the following command in the Terminal:

1npx @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:

1npx @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 API.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)
1import { API } from 'aws-amplify';
2import { createTodo, updateTodo, deleteTodo } from './graphql/mutations';
3import { GraphQLQuery } from '@aws-amplify/api';
4import { CreateTodoInput, CreateTodoMutation, UpdateTodoMutation, DeleteTodoMutation } from './API';
5
6const todo: CreateTodoInput = { name: "My first todo", description: "Hello world!" };
7
8/* create a todo */
9await API.graphql<GraphQLQuery<CreateTodoMutation>>({
10 query: createTodo,
11 variables: {
12 input: todo
13 }
14});
15
16/* update a todo */
17await API.graphql<GraphQLQuery<UpdateTodoMutation>>({
18 query: updateTodo,
19 variables: {
20 input: {
21 id: "ENTER_TODO_ID_HERE",
22 name: "Updated todo info"
23 }
24 }
25});
26
27/* delete a todo */
28await API.graphql<GraphQLQuery<DeleteTodoMutation>>({
29 query: deleteTodo,
30 variables: {
31 input: {
32 id: "ENTER_TODO_ID_HERE"
33 }
34 }
35});
1import { API } from 'aws-amplify';
2import { createTodo, updateTodo, deleteTodo } from './graphql/mutations';
3
4const todo = { name: "My first todo", description: "Hello world!" };
5
6/* create a todo */
7await API.graphql({
8 query: createTodo,
9 variables: {
10 input: todo
11 }
12});
13
14/* update a todo */
15await API.graphql({
16 query: updateTodo,
17 variables: {
18 input: {
19 id: "ENTER_TODO_ID_HERE",
20 name: "Updated todo info"
21 }
22 }
23});
24
25/* delete a todo */
26await API.graphql({
27 query: deleteTodo,
28 variables: {
29 input: {
30 id: "ENTER_TODO_ID_HERE"
31 }
32 }
33});
  • Queries - read data from the API (list and get operations)
1import { API } from 'aws-amplify';
2import { GraphQLQuery } from '@aws-amplify/api';
3import { listTodos } from './graphql/queries';
4import { ListTodosQuery } from './API';
5
6const todos = await API.graphql<GraphQLQuery<ListTodosQuery>>({ query: listTodos });
1import { API } from 'aws-amplify';
2import { listTodos } from './graphql/queries';
3
4const todos = await API.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: