Page updated Mar 6, 2024

Preview: AWS Amplify's new code-first DX (Gen 2)

The next generation of Amplify's backend building experience with a TypeScript-first DX.

Get started

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

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.

1import { Amplify } from 'aws-amplify';
2import config from './amplifyconfiguration.json';
3
4Amplify.configure(config);

Make sure you call Amplify.configure as early as possible in your application’s life-cycle. A missing configuration or NoCredentials error is thrown if Amplify.configure has not been called before other Amplify JavaScript APIs. Review the Library Not Configured Troubleshooting guide for possible causes of this issue.

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 endpoint and region values.

1import { Amplify } from 'aws-amplify';
2
3Amplify.configure({
4 API: {
5 GraphQL: {
6 // Provide endpoint and region information here
7 endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
8 region: 'us-east-1'
9 // Read next section on how to set the correct authorization mode for the API
10 }
11 }
12});

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:

1import { Amplify } from 'aws-amplify';
2
3Amplify.configure({
4 API: {
5 GraphQL: {
6 endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
7 region: 'us-east-1',
8 // Set the default auth mode to "apiKey" and provide the API key value
9 defaultAuthMode: 'apiKey',
10 apiKey: 'da2-xxxxxxxxxxxxxxxxxxxxxxxxxx'
11 }
12 }
13});
1import { Amplify } from 'aws-amplify';
2
3Amplify.configure({
4 API: {
5 GraphQL: {
6 endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
7 region: 'us-east-1',
8 // Set the default auth mode to "userPool"
9 defaultAuthMode: 'userPool'
10 }
11 }
12});
1import { Amplify } from 'aws-amplify';
2
3Amplify.configure({
4 API: {
5 GraphQL: {
6 endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
7 region: 'us-east-1',
8 // Set the default auth mode to "iam"
9 defaultAuthMode: 'iam'
10 }
11 },
12 Auth: {
13 Cognito: {
14 identityPoolId: "YOUR_IDENTITY_POOL_ID",
15 allowGuestAccess: true // set to false to not use the unauthenticated role
16 }
17 }
18});
1import { Amplify } from 'aws-amplify';
2
3Amplify.configure({
4 API: {
5 GraphQL: {
6 endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
7 region: 'us-east-1',
8 // Set the default auth mode to "OIDC"
9 defaultAuthMode: 'oidc'
10 }
11 }
12});

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 API: {
5 GraphQL: {
6 endpoint: 'https://abcxyz.appsync-api.us-east-1.amazonaws.com/graphql',
7 region: 'us-east-1',
8 // Set the default auth mode to "lambda"
9 defaultAuthMode: 'lambda'
10 }
11 }
12});

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});

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:

1import { Amplify } from 'aws-amplify';
2import config from './amplifyconfiguration.json';
3
4Amplify.configure(config, {
5 API: {
6 GraphQL: {
7 headers: async () => ({
8 'My-Custom-Header': 'my value'
9 })
10 }
11 }
12});

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 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)
1import { generateClient } from 'aws-amplify/api';
2import { createTodo, updateTodo, deleteTodo } from './graphql/mutations';
3
4const client = generateClient();
5
6const todo = { name: 'My first todo', description: 'Hello world!' };
7
8/* create a todo */
9await client.graphql({
10 query: createTodo,
11 variables: {
12 input: todo
13 }
14});
15
16/* update a todo */
17await client.graphql({
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 client.graphql({
29 query: deleteTodo,
30 variables: {
31 input: {
32 id: 'ENTER_TODO_ID_HERE'
33 }
34 }
35});
  • Queries - read data from the API (list and get operations)
1import { generateClient } from 'aws-amplify/api';
2import { listTodos } from './graphql/queries';
3
4const client = generateClient();
5
6const 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: