Calling an AWS AppSync API from a Lambda Function Using Node.js Fetch

2023-03-21

Calling an AWS AppSync API from a Lambda Function Using Node.js Fetch

Introduction

AWS AppSync has become a go-to service for building robust, scalable GraphQL APIs. But did you know that you can interact with an AppSync API just like a REST API? In this article, we'll explore how to call an AppSync API from an AWS Lambda function using a simple Node.js fetch with a POST call. We'll also demystify the notion that GraphQL is a complex beast by showing that it's essentially a REST API with an extra layer of flexibility.

GraphQL vs. REST

Before diving into the code, let's clarify what sets GraphQL apart from REST. In a REST API, you have predefined endpoints for each type of operation you want to perform. In contrast, GraphQL has a single endpoint that handles queries and mutations. This single endpoint takes a POST request with a payload describing what you want to do, making it incredibly flexible.

Example: REST API vs GraphQL Query

// REST API: GET request to fetch user data
fetch('https://api.example.com/users/1');

// GraphQL API: POST request to fetch user data
fetch('https://api.example.com/graphql', {
  method: 'POST',
  body: JSON.stringify({
    query: `
      query {
        user(id: 1) {
          id
          name
          email
        }
      }
    `
  })
});

Into the code

Setting Up Your Lambda Function

To call an AppSync API from a Lambda function, you'll need to set up a Node.js environment. AWS SDK is usually pre-installed in the Lambda Node.js runtime, but you'll need to include a fetch library.

Installing Dependencies

npm install node-fetch

Making the API Call

Now that we have our Lambda function set up, let's make the API call. We'll use a POST request, as all GraphQL queries and mutations are POST requests.

Example: Calling AppSync API from Lambda

const fetch = require('node-fetch');

exports.handler = async (event) => {
  const apiUrl = 'https://yourappsyncapi.appsync-api.us-east-1.amazonaws.com/graphql';
  const apiKey = 'your-appsync-api-key';
  
  const query = `
    query {
      listTodos {
        items {
          id
          name
          completed
        }
      }
    }
  `;

  const response = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      'x-api-key': apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ query })
  });

  const data = await response.json();
  return data;
};

Another alternative: Making the API Call Using AWS SDK

AWS SDK provides an AppSync client that can be used to make queries and mutations. Below is an example of how to set up a Lambda function to call an AppSync API using AWS SDK.

Example: Calling AppSync API from Lambda with AWS SDK

const AWS = require('aws-sdk');
AWS.config.update({ region: 'us-east-1' });

const appsync = new AWS.AppSync({ apiVersion: '2017-07-25' });
const apiKey = 'your-appsync-api-key';

exports.handler = async (event) => {
  const params = {
    apiId: 'your-appsync-api-id',
    query: `
      query {
        listTodos {
          items {
            id
            name
            completed
          }
        }
      }
    `,
    apiKey
  };

  try {
    const data = await appsync.startQueryExecution(params).promise();
    return data;
  } catch (error) {
    console.error('Error executing query:', error);
    throw new Error('Query execution failed');
  }
};

In this example, we first import the AWS SDK and configure it for our region. We then create an instance of the AppSync client and define our API key and query.

The startQueryExecution method is used to execute the query. It takes a params object that includes the apiId, query, and apiKey. The method returns a promise, which we await to get the query results.

Fetch vs. AWS SDK: Which to Choose?

  • Fetch: Use if you want a simple, straightforward way to make HTTP requests. It's less integrated but offers more control over the HTTP layer. It can also be the only alternative if the Lambda and the Appsync API are on different accounts and their permissions can't be configured easily.
  • AWS SDK: Use if you prefer a more integrated, AWS-native way to interact with AppSync. It's easier to maintain and debug but abstracts away some of the HTTP details.

Conclusion

Calling an AppSync API from a Lambda function using Node.js fetch is straightforward. It leverages the simplicity and flexibility of GraphQL, allowing you to interact with your API in a more dynamic way. By understanding that a GraphQL API is essentially a REST API with an extra layer, you can simplify your backend architecture and make more efficient API calls.

So, the next time you find yourself setting up a Lambda function to interact with AppSync, remember that a simple fetch call is all you need.