Build a simple Javascript app that calls the Unified.to API

In this tutorial, you’ll build a simple Javascript application that calls the Unified API to list candidates from Lever, an applicant tracking system (ATS). It assumes you have basic knowledge of:

  • HTML
  • Javascript
  • Web development

By the end of this tutorial, you’ll be able to:

  1. Activate integrations in Unified.to
  2. Create connections to third-party vendors e.g. Lever
  3. Embed Unified.to's widget to display integrations in your app
  4. Call the Unified API and display the results

Background

Unified.to is a platform that provides a unified (i.e. single) API for integrating various software applications. In this tutorial, we'll connect to Lever, an Applicant Tracking System (ATS) used by recruiters and talent teams. An ATS like Lever helps companies manage their hiring process by organizing candidate information, job postings, and application workflows.

However, oftentimes app developers will want to integrate with multiple vendors. Integrating directly with multiple platforms can be challenging due to differences in APIs and data models. This is where Unified.to comes in. It provides a standardized way to interact with multiple platforms through a unified API. This means you can write code once and potentially integrate with multiple systems without having to learn each individual API.

Prerequisites

Before we begin, make sure you have:

  1. Signed up for a Unified.to account
  2. Completed our Get Started guide in the app (optional, but recommended)
  3. Downloaded a code editor of your choice, like VS Code
  4. Installed NPM and Node.js on your system

Starter Code

We've prepared a simple JavaScript and HTML application for you to build upon, which can find here. This will serve as the foundation for our tutorial and we recommend that you download it and follow along. Run the commands below:

// inside the folder where you want to download the repo
git clone git@github.com:unified-to/unified-javascript-tutorial.git
cd unified-javascript-tutorial
npm i && npm run start

The app should now be available on localhost:1234. This repository contains a basic structure for a single-page application that we'll develop with Unified.to. Take a moment to familiarize yourself with the files we’ll be working with:

  • index.html: The main HTML file for our application.
  • app.js: Where we'll add our JavaScript code. It contains placeholders and predefined variables for your convenience.
  • .env: Where you’ll add sensitive information, like your API token.

Open the folder in your preferred code editor.

Retrieve your Workspace ID and API Token from Unified.to

You can find these values in your developer account under Settings > API Information. Record your Workspace ID and API Token in the .env file.

UNIFIED_WORKSPACE_ID = your_workspace_id_here;
UNIFIED_API_KEY = your_api_token_here;

You’ll use them later when making calls to the API.

Activate Lever in the Sandbox environment

The Sandbox environment is where you can activate, explore, and try out integrations in a safe and non-destructive environment.

Check that you are in the Sandbox environment

  1. Navigate to Integrations > Active Integrations
  2. Look for the environment dropdown near the top of the page. Click on the dropdown that contains 'ENV' and select 'ENV: SANDBOX'. Any subsequent actions you take will happen in the Sandbox environment.

Activate Lever

  1. On the same page (Active Integrations), search for 'Lever' by typing it into the search box.
  2. Click on the Lever card to open its details page.
  3. Leave the default settings as-is. Notice that since we’re in the Sandbox environment, the credentials are pre-filled with mock values. Lever uses OAuth 2 by default for authorization.
  4. At the bottom of the page, click 'Activate’.

The Lever integration is now activated in your Sandbox environment. This allows you to make test API calls and get a feel for the Unified API without needing to connect to a real Lever account.

Add the Unified.to Embedded Widget to your app

The Embedded Widget displays a list of your activated integrations. Your customers can use it to authorize access to third-party vendors for your app. We'll dynamically inject the widget script into the DOM using JavaScript, which allows us to use the environment variables we defined earlier.

  1. Open app.js and add the following code:
function injectUnifiedWidget() {
    const script = document.createElement('script');
    script.src = `https://api.unified.to/docs/unified.js?wid=${UNIFIED_WORKSPACE_ID}&did=unified_widget&env=Sandbox`;
    script.async = true;
    script.onload = () => {
        console.log('Unified widget script loaded successfully');
    };
    script.onerror = () => {
        console.error('Failed to load Unified widget script');
    };
    // The script will search the DOM for a div with the id "unified_widget"
    document.body.appendChild(script);
}

// Inject the widget on page load
document.addEventListener('DOMContentLoaded', () => {
    injectUnifiedWidget();
});
  1. In index.html, uncomment the following line:
<div id="unified_widget" class="mb-6"></div>

Now, when your application loads, it will dynamically inject the Unified.to widget into the DOM. Refresh the page, you should see the widget will appear displaying a list of activated integrations.

Handle and Store the Connection ID

When a user clicks on the Lever integration in the Unified.to widget, a new page will open where they will be asked to grant access to Lever before being redirected back to your app.

The redirect URL contains important parameters, including id , which represents the Connection ID. We need to store this ID for making subsequent calls to the Unified API.

Add the following code to app.js to handle the connection process:

function handleConnectionCallback() {
    const urlParams = new URLSearchParams(window.location.search);
    const connectionId = urlParams.get('id');

    if (connectionId) {
        console.log('New connection created:', connectionId);

        // Store the connectionId for later use
        localStorage.setItem('unifiedConnectionId', connectionId);
    } else {
        console.log('No connection ID found in URL parameters');
    }
}

// Execute the handler when the page loads
window.addEventListener('load', handleConnectionCallback);

Warning: Storing the Connection ID in localStorage is used here for simplicity and learning purposes only. In a production environment, you should securely store this information server-side, associated with the user's account. Refer to our guide on How to Associate a Connection ID with your End-User for best practices.

Create and Verify the Connection

Let’s walk through creating a connection to confirm that it works.

Create the Connection

  1. In the widget, click on the Lever integration.
  2. Authorization Flow:
    • A new page will open with a disclaimer that you are on the Tester plan.
    • Click Continue to grant access to Lever. Note: The authorization flow is simplified in the Sandbox environment. In Production, your user will be shown the scopes you are requesting and asked to grant you access.
  3. After granting access, you'll be automatically redirected back to your app.

Verify the Connection

Let's verify that the connection was created successfully:

  1. Check the URL:
    • Look at the URL in your browser's address bar.
    • You should see a parameter id in the URL. This is your Connection ID.
    • For example, the URL might look like: http://localhost:3000?id=abc123...
  2. Console Output:
    • Open your browser's developer tools.
    • Go to the Console tab.
    • You should see a message similar to: New connection created: abc123...
    • This confirms that our handleConnectionCallback function has captured the Connection ID.
  3. Verify Local Storage (Optional):
    • In the developer tools, go to the Application tab.
    • Under Storage, select Local Storage and your domain.
    • You should see an item named unifiedConnectionId with the value matching the ID from the URL.

Set Up API Call to the Unified ATS Endpoint

In this step, we'll implement the API call to fetch candidate data from the Unified ATS endpoint.

Implement the API call function

In app.js, add the following function to fetch ATS candidate data from the ATS endpoint:

async function fetchATSCandidates(connectionId) {
    const options = {
        method: 'GET',
        url: `https://api.unified.to/ats/${connectionId}/candidate`,
        headers: {
            authorization: `bearer ${UNIFIED_API_KEY}`,
        },
        params: {
            limit: 50,
            offset: 0,
        },
    };

    try {
        const response = await axios.request(options);
        return response.data;
    } catch (error) {
        console.error('Error fetching ATS candidates:', error);
        return null;
    }
}

API Reference: ATS Candidate

Fetch and display candidates in the UI

In index.html, uncomment the following lines:

<div class="mt-5">
    <button
        id="fetchCandidatesBtn"
        type="button"
        class="inline-flex items-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500"
    >
        Fetch candidates
    </button>
</div>
<div class="mt-5">
    <ul
        id="candidates-list"
        role="list"
        class="divide-y divide-gray-100"
    ></ul>
</div>

Implement the click handler

Add the following code to your app.js file to handle the button click and display the results:

function displayCandidates(candidates) {
    const candidatesList = document.getElementById('candidates-list');
    candidatesList.innerHTML = '<h2>Candidates:</h2>';

    candidates.forEach((candidate) => {
        const candidateElement = document.createElement('div');
        candidateElement.innerHTML = `
      <li class="flex justify-between gap-x-6 py-5">
        <div class="flex min-w-0 gap-x-4">
            <img class="h-12 w-12 flex-none rounded-full bg-gray-50" src="https://ui-avatars.com/api/?name=${encodeURIComponent(
                candidate.name || 'na'
            )}&background=random">
            <div class="min-w-0 flex-auto">
                <p class="text-sm font-semibold leading-6 text-gray-900">${candidate.name}</p>
                <p class="mt-1 truncate text-xs leading-5 text-gray-500 lowercase">${
                    candidate.emails?.[0]?.email
                }</p>
            </div>
        </div>
        </li>
    `;
        candidatesList.appendChild(candidateElement);
    });
}

document.getElementById('fetchCandidatesBtn').addEventListener('click', async () => {
    const connectionId = localStorage.getItem('unifiedConnectionId');

    if (!connectionId) {
        console.error('No connection ID found. Please connect to Lever first.');
        return;
    }

    const candidates = await fetchATSCandidates(connectionId);

    if (candidates) {
        displayCandidates(candidates);
    } else {
        console.log('No candidates found or error occurred');
        document.getElementById('candidatesList').innerHTML =
            '<p>No candidates found or an error occurred.</p>';
    }
});

Call the Unified API

Now, let's test our application to ensure everything is working correctly.

Click Fetch Candidates. You should see a list of candidates appear on your screen. Since we're working in the Sandbox environment, these will be mock candidates generated by Unified.to.

Results of calling the API

Troubleshooting: If you don't see any candidates or encounter an error, check the browser console for any error messages or verify that your Unified API Key is correctly set in the .env file.

Summary

Congratulations! You've built a Javascript app that can call the Unified.to API and fetch candidates from Lever. In this tutorial, you saw how to:

  • Activate integrations in Unified.to
  • Create connections by granting access to third-party vendors
  • Add the Unified.to Embedded Widget to your app
  • Make API calls to our unified API

Next Steps

From here, you can start adding integrations from Unified.to into your own project. The following resources can help you on your way:

  • Use one of our SDKs
  • Get familiar with webhooks
  • Explore how to manage your connections and webhooks through our management API

Happy building!

Are we missing anything? Let us know
Was this page helpful?