Fetching data from a source and persisting them are vital parts of any application. In this tutorial, we'll learn about fetching data from a third-party REST API and persisting it in the Freshworks infrastructure using the Request method and Key-Value Storage respectively.

Request Method

Request method comes built-in with the Freshworks platform to send HTTP requests from an app. The request method is a suggested alternative over the regular HTTP clients like jQuery.ajax(..) or fetch(..).

There are various reasons to use the Request method over conventional HTTP clients, which are as follows,

Data Storage

The Data Storage also comes built-in with the Freshworks developer platform. Freshworks data storage offers Key-Value storage and Entity storage.

In key-value storage you can save JSON objects up to the size of 8kb. Although there is a size restriction on objects, there is no restriction on the number of objects you can store in the Freshworks data storage.

Entity storage allows you to define your custom objects (entities) and use the custom object as the entity schema for data storage which also features querying capabilities with filters for data retrieval from the entity storage.

In this tutorial, we will be using the key-value storage.

Advantages of using Freshworks Data Storage are,

What we'll build?

In this tutorial, we'll build a fun Freshdesk app that fetches the current location(latitude and longitude) of the International space station using a free REST API.

Prerequisites

Clone the boilerplate

Once you have the prerequisites ready, clone the boilerplate from the below repository

git clone  https://github.com/freshworks-developers/request-method-and-data-storage_Freshdesk.git

The cloned repository will have two folders

Folder structure of the boilerplate app

Boiler plate App Strucuture

The above image shows the folder structure of the boilerplate app, the functionalities of the files are as follows

To run either of the apps change the directory to the corresponding folder( /start or /completed) and run fdk run in the terminal to start the localhost.

The localhost should start with the messages displayed in the screenshot below

Localhost

Once the localhost is started with the above message, open a ticket page and append "?dev=true" in the URL (eg: https://you_portal_name.freshdesk.com/a/tickets/1?dev=true), The app should render in the ticket_sidebar location as shown in the highlighted section of the below screenshot.

Boilerplate

Now that we have the basics covered, let's extend the boilerplate to build our app.

First, let us define our request template in configs/requests.json.

{
  "getDataFromISS": {
    "schema": {
      "method": "GET",
      "protocol": "https",
      "host": "api.wheretheiss.at",
      "path": "/v1/satellites/25544",
      "headers": {
        "Content-Type": "application/json"
      }
    }
  }
}

The request getDataFromISS will make an HTTP GET call. Note how we have identified the host and path of the same URL for the request template.

In app/index.html, add the Client JS resource.

<script src="{{{appclient}}}"></script>

Let us now make the Request method call from app/scripts/app.js.

/**
 * Function to Fetch location of International Space Station from the REST API
 * 
 */

async function fetchData() {

  // API endpoint to fetch the current location of the International Space Station defined in config/requests.json

  try {
    let location = await client.request.invokeTemplate("getDataFromISS", { })
    alert('location of International Space Station  :-' + JSON.stringify(location));
  } catch (error) {
    handleErr(error)
  }

}

And declare the request template used in the app in manifest.json. And the final version of the manifest.json would look like -

{
  "platform-version": "2.3",
  "product": {
    "freshdesk": {
      "location": {
        "ticket_sidebar": {
          "url": "index.html",
          "icon": "styles/images/icon.svg"
        }
      },
      "requests":{
        "getDataFromISS":{}
      }
    }
  },
  "engines": {
    "node": "18.13.0",
    "fdk": "9.0.0"
  }
}

Test the feature

Let's start the localhost and verify that our changes works as intended.

Fetch Data From the above GIF we can see that by clicking on the fetch button, we can fetch the location of the international space station successfully and display it in the notification.

Now that we fetched the data from the REST API via the Request method, let's persist it to the Data Storage for later use.

Update the below code in app/scripts/app.js.

/**
* Function to save the location in data storage
* @param {*} data Object
*/
function saveInDataStorage(data) {
try {
    let response = await client.db.set("location", location)
    showNotify("success", "Location saved successfully in the Data Storage");
    console.log(response)
  } catch (error) {
    handleErr(error)
  }
}

The above function uses the db method exposed by the client object to set the data in the Freshworks Data Storage.

Invoke the saveInDataStorage(location) function with the location as the parameter which we got from the request API, replace the alert message with the below code in the fetchData(){...} function.

  // Invoke the saveInDataStorage(data) function to save the location in the data storage
  saveInDataStorage({ 'latitude': JSON.parse(location.response).latitude, 'longitude': JSON.parse(location.response).longitude })

Let's restart the localhost and test the functionality as shown in the below GIF

Fetch and Save Data

From the above GIF We can see that a notification is displayed to acknowledge the data is saved successfully in the data storage.

We have the data saved in the Freshwoks Data Storage, the next step is to fetch the location from data storage and display it as a notification.

/**
* Function to fetch the location of International space station
*/
function fetchFromDataStorage() {
  try {
    let location = await client.db.get("location")
    showNotify('success', `The location ISS from the Data Storage is Latitude: ${location.latitude} , Longitude: ${location.longitude}`)
    console.info('data', location);
  } catch (error) {
    handleErr(error)
  }
}

The above code snippet fetches the location from the freshworks data storage and displays it as a notification.

Let us test if we can fetch the data from the data storage

Fetch From DB

From the above GIF we can verify that the data can be successfully fetched from the Data storage and displays it correctly as a notification.

What we've learned?

In this tutorial, we've learned,

✅ How to use the Request Method to fetch data from a REST API ✅ How to persist and fetch data from the Freshworks Key-Value storage.

What's next?

Now that you are familiar with the data storage, and the request method, you can expand your knowledge by,

✅ By exploring advanced data storage options to build more complex solutions backed by data storage. ✅ Use Request method to make complex API calls to Create(POST) and Update(PUT) endpoints, with authentication.