Page updated Nov 29, 2023

Connect your app code to 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:

  • your cloud sandbox with an Amplify Data resource up and running (npx amplify sandbox)
  • A frontend application set up. For instructions on setting up an app, see the quickstart for Amplify (Gen 2)
  • npm installed

Install the Amplify Library

You need the Amplify Library to connect to your Data backend. To install the the Amplify client library, navigate to your frontend's root folder and run the following command in your Terminal:

npm add aws-amplify
1npm add aws-amplify

Configure the Amplify Library

You will then configure the library to connect with your Amplify Data's backend API:

When you deploy you're iterating on your backend (npx amplify sandbox), an amplifyconfiguration.json file is generated for you. This file contains your API's endpoint information and auth configurations. Add the following code to your app's entrypoint to initialize and configure the Amplify client library:

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

Generate the Amplify Data client

Once the Amplify library is configured, you can generate a "Data client" for your frontend code to make fully-typed API requests to your backend. To generate a new Data client, use the following code:

import { generateClient } from 'aws-amplify/data'; import type { Schema } from '@/backend/data/resource'; // Path to your backend resource definition const client = generateClient<Schema>(); // Now you should be able to make CRUDL operations with the // Data client async function fetchTodos() { const { data: todos, errors } = await client.models.Todo.list(); }
1import { generateClient } from 'aws-amplify/data';
2import type { Schema } from '@/backend/data/resource'; // Path to your backend resource definition
3
4const client = generateClient<Schema>();
5
6// Now you should be able to make CRUDL operations with the
7// Data client
8async function fetchTodos() {
9 const { data: todos, errors } = await client.models.Todo.list();
10}

Configure authorization mode

The Authorization Mode is determines how a request should be authorized with the backend. By default, Amplify Data uses the "userPool" authorization which uses the signed-in user credentials to sign an API request. If you use public authorization rules for you data models, you need to use "apiKey" an an authorization mode. Review Customize your auth rules to learn more about which authorization modes to choose for which type of request. A Default Authorization Mode is provided as part of the amplifyconfiguration.json that is generated upon a successful deployment.

You can generate different Data clients with different authorization modes or pass in the authorization mode at the request time.

Set authorization mode on a Data client

To apply the same authorization mode on all requests from a Data client, specify the authMode parameter on the generateClient function.

import { generateClient } from 'aws-amplify/data'; import type { Schema } from '@/backend/data/resource'; // Path to your backend resource definition const client = generateClient<Schema>({ authMode: 'apiKey' });
1import { generateClient } from 'aws-amplify/data';
2import type { Schema } from '@/backend/data/resource'; // Path to your backend resource definition
3
4const client = generateClient<Schema>({
5 authMode: 'apiKey'
6});

Set authorization mode on the request-level

You can also specify the authorization mode on each individual API request. This is useful if your application typically only uses one authorization mode with a small number of exceptions.

const { data: todos, errors } = await client.models.Todo.list({ authMode: 'apiKey' });
1const { data: todos, errors } = await client.models.Todo.list({
2 authMode: 'apiKey'
3});

Set custom request headers

When working with the Amplify Data endpoint, you may need to set request headers for authorization purposes or to pass additional metadata from your frontend to the backend API. This is done by specifying a headers parameter into the configuration. You can define headers either on a per Data client-level or on a per-request level:

import type { Schema } from '@/backend/schema'; import { generateClient } from 'aws-amplify/data'; const client = generateClient<Schema>({ headers: { 'My-Custom-Header': 'my value' } });
1import type { Schema } from '@/backend/schema';
2import { generateClient } from 'aws-amplify/data';
3
4const client = generateClient<Schema>({
5 headers: {
6 'My-Custom-Header': 'my value'
7 }
8});

The examples above show you how to set static headers but you can also programmatically set headers by specifying an async function for headers:

import type { Schema } from '@/backend/schema'; import { generateClient } from 'aws-amplify/data'; const client = generateClient<Schema>({ headers: async (requestOptions) => { console.log(requestOptions); /* The request options allow you to customize your headers based on the request options such as http method, headers, request URI, and query string. These options are typically used to create a request signature. { method: '...', headers: { }, uri: '/', queryString: "" } */ return { 'My-Custom-Header': 'my value' }; } });
1import type { Schema } from '@/backend/schema';
2import { generateClient } from 'aws-amplify/data';
3
4const client = generateClient<Schema>({
5 headers: async (requestOptions) => {
6 console.log(requestOptions);
7 /* The request options allow you to customize your headers based on the request options such
8 as http method, headers, request URI, and query string. These options are typically used
9 to create a request signature.
10 {
11 method: '...',
12 headers: { },
13 uri: '/',
14 queryString: ""
15 }
16 */
17 return {
18 'My-Custom-Header': 'my value'
19 };
20 }
21});

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 customize the data client with different authorization modes and custom headers.

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: