Page updated Jan 16, 2024

Connect to data from server-side runtimes

You can call an AppSync GraphQL API from a Node.js app or a Lambda function. Take a basic Todo app as an example:

1type Todo @model @auth(rules: [{ allow: public }]) {
2 name: String
3 description: String
4}

This API will have operations available for Query, Mutation, and Subscription. Let's take a look at how to perform both a query as well as a mutation from a Lambda function using Node.js.

First, create a Lambda function with amplify add function and make sure to give access to your GraphQL API when prompted by the CLI to grant access to other resources in the project.

1amplify add function
2? Select which capability you want to add: Lambda function (serverless function)
3? Provide an AWS Lambda function name: myfunction
4? Choose the runtime that you want to use: NodeJS
5? Choose the function template that you want to use: Hello World
6
7Available advanced settings:
8- Resource access permissions
9- Scheduled recurring invocation
10- Lambda layers configuration
11- Environment variables configuration
12- Secret values configuration
13
14? Do you want to configure advanced settings? Yes
15? Do you want to access other resources in this project from your Lambda function? Yes
16? Select the categories you want this function to have access to. api
17? Select the operations you want to permit on <YOUR_API_NAME> Query, Mutation, Subscription
18
19You can access the following resource attributes as environment variables from your Lambda function
20 API_<YOUR_API_NAME>_GRAPHQLAPIENDPOINTOUTPUT
21 API_<YOUR_API_NAME>_GRAPHQLAPIIDOUTPUT
22 API_<YOUR_API_NAME>_GRAPHQLAPIKEYOUTPUT
23 ENV
24 REGION

The examples on this page use node-fetch to make a HTTP request to your GraphQL API. When the Node.js v18 runtime is released for Lambda this dependency can be removed in favor of native fetch To get started, add the node-fetch module as a dependency:

1{
2 "name": "myfunction",
3+ "type": "module",
4 "version": "2.0.0",
5 "description": "Lambda function generated by Amplify",
6 "main": "index.js",
7 "license": "Apache-2.0",
8+ "dependencies": {
9+ "node-fetch": "^3.2.3"
10+ },
11 "devDependencies": {
12 "@types/aws-lambda": "^8.10.92"
13 }
14}

Query

Using an API Key for authenticating your requests, you can query the GraphQL API to get a list of all Todos.

1import { default as fetch, Request } from 'node-fetch';
2
3const GRAPHQL_ENDPOINT = process.env.API_<YOUR_API_NAME>_GRAPHQLAPIENDPOINTOUTPUT;
4const GRAPHQL_API_KEY = process.env.API_<YOUR_API_NAME>_GRAPHQLAPIKEYOUTPUT;
5
6const query = /* GraphQL */ `
7 query LIST_TODOS {
8 listTodos {
9 items {
10 id
11 name
12 description
13 }
14 }
15 }
16`;
17
18/**
19 * @type {import('@types/aws-lambda').APIGatewayProxyHandler}
20 */
21export const handler = async (event) => {
22 console.log(`EVENT: ${JSON.stringify(event)}`);
23
24 /** @type {import('node-fetch').RequestInit} */
25 const options = {
26 method: 'POST',
27 headers: {
28 'x-api-key': GRAPHQL_API_KEY
29 },
30 body: JSON.stringify({ query, variables })
31 };
32
33 const request = new Request(GRAPHQL_ENDPOINT, options);
34
35 let statusCode = 200;
36 let body;
37 let response;
38
39 try {
40 response = await fetch(request);
41 body = await response.json();
42 if (body.errors) statusCode = 400;
43 } catch (error) {
44 statusCode = 400;
45 body = {
46 errors: [
47 {
48 status: response.status,
49 message: error.message,
50 stack: error.stack
51 }
52 ]
53 };
54 }
55
56 return {
57 statusCode,
58 body: JSON.stringify(body)
59 };
60};

Mutation

In this example you create a mutation showing how to pass in variables as arguments to create a Todo record.

1import { default as fetch, Request } from 'node-fetch';
2
3const GRAPHQL_ENDPOINT = process.env.API_<YOUR_API_NAME>_GRAPHQLAPIENDPOINTOUTPUT;
4const GRAPHQL_API_KEY = process.env.API_<YOUR_API_NAME>_GRAPHQLAPIKEYOUTPUT;
5
6const query = /* GraphQL */ `
7 mutation CREATE_TODO($input: CreateTodoInput!) {
8 createTodo(input: $input) {
9 id
10 name
11 createdAt
12 }
13 }
14`;
15
16/**
17 * @type {import('@types/aws-lambda').APIGatewayProxyHandler}
18 */
19export const handler = async (event) => {
20 console.log(`EVENT: ${JSON.stringify(event)}`);
21
22 const variables = {
23 input: {
24 name: 'Hello, Todo!'
25 }
26 };
27
28 /** @type {import('node-fetch').RequestInit} */
29 const options = {
30 method: 'POST',
31 headers: {
32 'x-api-key': GRAPHQL_API_KEY
33 },
34 body: JSON.stringify({ query, variables })
35 };
36
37 const request = new Request(GRAPHQL_ENDPOINT, options);
38
39 let statusCode = 200;
40 let body;
41 let response;
42
43 try {
44 response = await fetch(request);
45 body = await response.json();
46 if (body.errors) statusCode = 400;
47 } catch (error) {
48 statusCode = 400;
49 body = {
50 errors: [
51 {
52 status: response.status,
53 message: error.message,
54 stack: error.stack
55 }
56 ]
57 };
58 }
59
60 return {
61 statusCode,
62 body: JSON.stringify(body)
63 };
64};

IAM Authorization

Let's take a look at another example schema that uses iam authorization.

1type Todo @model @auth(rules: [{ allow: private, provider: iam }]) {
2 name: String
3 description: String
4}

The CLI will automatically configure the Lambda execution IAM role to call the GraphQL API. Before writing your Lambda function you will first need to install the appropriate AWS SDK v3 dependencies:

1{
2 "name": "myfunction",
3+ "type": "module",
4 "version": "2.0.0",
5 "description": "Lambda function generated by Amplify",
6 "main": "index.js",
7 "license": "Apache-2.0",
8+ "dependencies": {
9+ "@aws-crypto/sha256-js": "^2.0.1",
10+ "@aws-sdk/credential-provider-node": "^3.76.0",
11+ "@aws-sdk/protocol-http": "^3.58.0",
12+ "@aws-sdk/signature-v4": "^3.58.0",
13+ "node-fetch": "^3.2.3"
14+ },
15 "devDependencies": {
16 "@types/aws-lambda": "^8.10.92"
17 }
18}

Then, the following example will sign the request to call the GraphQL API using IAM authorization.

1import crypto from '@aws-crypto/sha256-js';
2import { defaultProvider } from '@aws-sdk/credential-provider-node';
3import { SignatureV4 } from '@aws-sdk/signature-v4';
4import { HttpRequest } from '@aws-sdk/protocol-http';
5import { default as fetch, Request } from 'node-fetch';
6
7const { Sha256 } = crypto;
8const GRAPHQL_ENDPOINT = process.env.API_<YOUR_API_NAME>_GRAPHQLAPIENDPOINTOUTPUT;
9const AWS_REGION = process.env.AWS_REGION || 'us-east-1';
10
11const query = /* GraphQL */ `
12 query LIST_TODOS {
13 listTodos {
14 items {
15 id
16 name
17 description
18 }
19 }
20 }
21`;
22
23/**
24 * @type {import('@types/aws-lambda').APIGatewayProxyHandler}
25 */
26export const handler = async (event) => {
27 console.log(`EVENT: ${JSON.stringify(event)}`);
28
29 const endpoint = new URL(GRAPHQL_ENDPOINT);
30
31 const signer = new SignatureV4({
32 credentials: defaultProvider(),
33 region: AWS_REGION,
34 service: 'appsync',
35 sha256: Sha256
36 });
37
38 const requestToBeSigned = new HttpRequest({
39 method: 'POST',
40 headers: {
41 'Content-Type': 'application/json',
42 host: endpoint.host
43 },
44 hostname: endpoint.host,
45 body: JSON.stringify({ query }),
46 path: endpoint.pathname
47 });
48
49 const signed = await signer.sign(requestToBeSigned);
50 const request = new Request(endpoint, signed);
51
52 let statusCode = 200;
53 let body;
54 let response;
55
56 try {
57 response = await fetch(request);
58 body = await response.json();
59 if (body.errors) statusCode = 400;
60 } catch (error) {
61 statusCode = 500;
62 body = {
63 errors: [
64 {
65 message: error.message
66 }
67 ]
68 };
69 }
70
71 return {
72 statusCode,
73 body: JSON.stringify(body)
74 };
75};