Let's make API request

To create a ticket in Freshservice, Freshservice provides an API that can be utilised from anywhere with the required authentication to create a ticket.

From our app, let’s make an API with the domain and credentials from the OAuth and iparams configurations.

Freshworks Developer Platform provides a Request Method feature to make API from the app. It has the following advantages over using a third-party library to make API from the frontend and serverless app. They are as follows,

  • Provides Static origin IP for the APIs
  • Avoids Cross-Origin Resource Sharing (CORS) check on the browser by using a Freshworks Platform as a proxy.
  • Securely accessing credentials and secrets from secure installation parameters.
  • Using native OAuth handshake mechanism from Freshworks Developer Platform.

Let’s create a API schema for making an API.

Create a JSON file with the name requests.json under /config folder and paste the following code in it.

config/requests.json file
{
  "createTicket": {
    "schema": {
      "method": "POST",
      "host": "<%= iparam.freshservice_domain %>",
      "path": "/api/v2/tickets",
      "headers": {
        "Authorization": "Bearer <%= access_token %>",
        "Content-Type": "application/json"
      }
    },
    "options": {
      "oauth": "freshservice"
    }
  }
}

In the request template, we define the URL, authentication mechanism, API endpoint path. The request body will be defined where this API schema will be used. This API schema template ensures consistency and ease of maintenance in making APIs from the app. We use the OAuth access token, which serves as the bearer token for authenticating your requests to the Freshservice API.

Let's define this request template under a new common module to the app in the manifest.json file as follows:

manifest.json file
{
  {
    "platform-version": "3.0",
    "modules": {
      "common": {
        "requests": {
          "createTicket": {}
        }
      },
      "service_ticket": {
        "location": {
          "ticket_sidebar": {
            "url": "index.html",
            "icon": "styles/images/wave.png"
          }
        }
      }
    }
  }
}

Next up, let’s use this Request template schema in the app functionality.

  1. In the app.js file, change this line in the init() function from client.events.on('app.activated', renderText); to client.events.on('app.activated', onAppActivated); and remove the complete renderText() function.
  2. Add the following functions to the app/app.js file.
app/app.js file
function onAppActivate() {
  // Fetch logged-in user details
  client.data.get("loggedInUser").then(
    function (data) {
      // Set agent name and update UI
      window.agent = data.loggedInUser.user.name;
      document.getElementById("agentName").textContent = `Hello ${agent},`;

      // Attach 'sayHello' function to a button click event
      document
        .getElementById("btnSayHello")
        .addEventListener("fwClick", sayHello);
    },
    function (error) {
      console.error("Error: Failed to fetch loggedInUser details");
      console.error(error);
    }
  );
}
async function sayHello() {
  try {
    await createTicket();
    
    console.info("Successfully created ticket in Freshservice");
    showNotification("success", "Successfully created a ticket to say hello");
    showBanner("Freshservice talks in tickets, check for new ticket.");
  } catch (error) {
    console.error("Error: Failed to create a ticket");
    console.error(error);
    showNotification("danger", "Failed to create a ticket.");
  }
}

async function createTicket() {
  // Predefined ticket details
  const ticketDetails = {
    email: "puppycat@email.com",
    subject: `Hello`,
    priority: 1,
    description: `Hey ${agentName} 👋, First HELLO always inspires!`,
    status: 2,
  };

  // Invoke Freshworks API to create a ticket
  await client.request.invokeTemplate("createTicket", {
    body: JSON.stringify(ticketDetails)
  });
}

We do the following in this code,

  • When the app is activated, get the logged-in user details that contains the agent’s name.
  • Display the agent’s name in a text field in the app.
  • Listen to the click event of the “Say Hello” button and call the sayHello() function in turn calls the createTicket() function that creates a ticket.
  • When creating a ticket, we use the created request template and pass the requet body according to our need.

When the ticket creation succeeds or fails, we show notification and update the new ticket information in the app UI. These utility functions are missing. Let’s also add them to the app.js file.

function showNotification(type, message) {
  return client.interface.trigger("showNotify", {
    type: type,
    message: message,
  });
}

function showBanner(value) {
  // Update the banner content
  document.getElementById("newTicketBanner").value = value;
}

Now, test the app with the complete flow until the ticket creation.

  1. Run the app with the fdk run command and view the app in the ticket details page of Freshservice.
  2. Open the app in the ticket details page sidebar and click on the “Say Hello” button.
  3. The app would create a ticket in Freshservice, show a notification for the same and updates the app UI with the ticket details.
  4. You can find a new ticket being created in your Freshservice portal in the tickets list page.

You can refer to the complete app in this repository.

We have completed the app but there are some things to remember and consider while building the app and maintaining it. Let’s see what are these design considerations.