DEV Community

Praneet Nadkar
Praneet Nadkar

Posted on

Call AWS AppSync API from JS

AppSync can do everything GraphQL specifies and also has additional features like authentication, authorization, filtering the data you return and the operations that the clients can perform, depending on which user is in.

AppSync supports Cognito, API Key, IAM permissions, and Open ID Connect and even provides support for DynamoDB, AWS Lambda, Elasticsearch, HTTP, and RDS as data sources.

Now to call this AppSync api, it also provides a code generator command with the AWS Amplify CLI which will generate a client code to call the API for you with the AWS Configuration file.

To integrate your app with the client, make sure you have AWS Amplify CLI installed. You can install it using this command:

npm install -g @aws-amplify/cli
Enter fullscreen mode Exit fullscreen mode

And then finally

amplify add codegen --apiId <API_ID_HERE>
Enter fullscreen mode Exit fullscreen mode

This will generate a .ts file which will make you reach pretty much there to integrate.

However, what if you want to call the API using JS only. I started to dig at many places but didn't find anything concrete. Here is my approach to call the AWS AppSync API using fetch()

var configText = '';

const configuration = 'awsconfiguration.json';

/**
 * API module for calling the AWS AppSync GraphQL API
 * @module API
 */

/**
 * Call this if a mutation has to be run for the GraphQL API.
 * This method will call AWS AppSync GraphQL API with the mutation sent as a parameter.
 * The mutationQuery parameter should be of proper format, else the API call will fail. 
 * @module mutation
 * @param { mutationQuery } mutationQuery This is the mutation that has to be called for in GraphQL
*/
function mutation(mutationQuery) {
    callAPI(mutationQuery);
}

/**
 * This method will call AWS AppSync GraphQL API with the query sent as a parameter
 * The getQuery parameter should be of proper format, else the API call will fail 
 * @param { getQuery } getQuery This is the query that has to be called for in GraphQL
*/
function query(getQuery) {
    callAPI(getQuery);
}

/**
 * This method calls the AWS AppSync GraphQL API. The path and options to call the API
 * is read via the AWS Config file.
 * @param { query } query This is the query, mutation or subscription that has to be called for in GraphQL
 * @throws {UnauthenticatedError} When the user is authentication to AWS fails.
*/
function callAPI(query){
    readAwsConfiguration(configuration); 
    // this obj will have all the configurations for AWS AppSync
    var obj = JSON.parse(configText);    

    // if the jwt is null, then the user authentication has not happened
    // in such a case, we will raise an errot that the user auth is required
    if(localStorage.getItem('jwt') === null)
    {
        throw new Error('User authentication is required to access the API. ');
    }

    const opts = {
        method: 'POST',
        headers:
        {
            'Content-Type': 'application/json',
            'aws_appsync_region':  obj.AppSync.Default.Region,
            'aws_appsync_authenticationType': obj.AppSync.Default.AuthMode,
            Authorization:  localStorage.getItem('jwt')
        },

        body: query
    };

    const url = obj.AppSync.Default.ApiUrl;

    fetch(url, opts)
        .then(res => res.json())
        .then(console.log)
        .catch(console.error);
}

/**
 * This method reads the aws configuration file. The config file has the AppSync URL,
 * Auth type and region details for the API
 * @param { file } file This is the file path from where the file has to be read
*/
function readAwsConfiguration(file) {

    var rawFile = new XMLHttpRequest(); // XMLHttpRequest (often abbreviated as XHR) is a browser object accessible in JavaScript that provides data in XML, JSON, but also HTML format, or even a simple text using HTTP requests.
    rawFile.open('GET', file, false); // open with method GET the file with the link file ,  false (synchronous)
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) // readyState = 4: request finished and response is ready
        {
            if (rawFile.status === 200) // status 200: "OK"
            {
                var allText = rawFile.responseText; //  Returns the response data as a string
                configText = allText;
            }
        }
    }

    rawFile.send(null); //Sends the request to the server Used for GET requests with param null
}
Enter fullscreen mode Exit fullscreen mode

Here I am reading the AWS Configuration from the file awsconfiguration.json
This file has the AWS Configuration with the AppSync URL, Region, AuthMethod etc.
In case if you are wondering from where one should get the configuration json file, you can download it from your AppSync API page.

Please note that the I have added a header named 'Authorization'. This has the JWT which will be used for authentication.

Note: If you are using the AWS Cognito, this value should be fetched from

signInUserSession.accessToken.jwtToken
Enter fullscreen mode Exit fullscreen mode

Finally, to call the API, all we have to do is this:

const mutationQuery = JSON.stringify({
        query: `mutation {
            updatePost(input: {postId:"asd97jd-kjd78-alfd"                  
                  authoredBy:"Sam"
                  editedBy:"Jonathan" }) {
              postId
              authoredBy
              editedBy              
            }
          }
          `
    });

    mutation(mutationQuery);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)