70 %
Chris Biscardi

How to query an AppSync GraphQL API from within a Lambda

Accessing an AppSync GraphQL API protected by IAM authorization from inside a Lambda requires that you either manually sign your request with a V4 signature or take advantage of the aws-appsync package.

Because we're using the aws-appsync package here, we'll also need a fetch polyfill.

my-lambda.js
JS
const appsync = require("aws-appsync");
const gql = require("graphql-tag");
require("cross-fetch/polyfill");
const graphqlClient = new appsync.AWSAppSyncClient({
url: process.env.GRAPHQL_API,
region: "us-west-2",
auth: {
type: "AWS_IAM",
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
sessionToken: process.env.AWS_SESSION_TOKEN,
},
},
fetchPolicy: "network-only",
disableOffline: true,
});
const query = gql`
query GetWorkspaces {
workspaces {
id
name
}
}
`;
exports.handler = async (event) => {
const results = await graphqlClient.query({ query });
console.log({ results });
return {
statusCode: 200,
body: JSON.stringify({
data: results.data,
errors: results.errors
}),
};
};

Note that you'll also need to give the lambda access to query the AppSync API. If you're using CDK, you can use the .grant* set of functions on the AppSync API. Where appsyncApi is an appsync.GraphqlApi and clientLambda is a lambda.Function.

cdk-stack.js
JS
appsyncApi.grantQuery(clientLambda);