Creating a Node.js service application that connects with OnCall Health's API

🚧

This guide is ideal for intermediate-level developers

To gain value from this guide, you'll need a decent understanding of JavaScript and REST APIs. Avoid copying and pasting code unless you understand how it works – especially when building an application that uses an OnCall Health API key, which grants access to sensitive patient data.

In this guide, we'll walk you through the process of creating a Node.js application that makes server-side requests to OnCall Health's API. You can subsequently deploy this program and use it when building additional applications that need to interact with OnCall Health's API.

There are three key benefits of using a Node.js application for this purpose:

  1. Security: Your OnCall Health API key can be used to access patient records stored in OnCall Health. Limiting access to this API key (even within your own development team) is consequently a good practice. A Node.js application facilitates this by letting your developers make calls to it rather than interacting with OnCall Health's API directly.

  2. Convenience: If you're building multiple applications that need to interact with OnCall Health's API, those requests can get repetitive very quickly. Consolidating them in a Node.js application will keep your code DRY.

  3. Ease of maintenance: Node.js is among the most popular web development frameworks, meaning developers on your team will have tons of resources and documentation at their disposal if the Node.js application we're building in this guide becomes an important part of your tech stack.

With those benefits in mind, let's jump in.

Before you get started

To follow along with this guide, you'll need an OnCall Health API key. Click here to learn more about how to access this key, which is only available to active customers.

When following this guide, please also ensure you're using a secure (non-shared) computer. Anyone with access to your computer will be able to see your OnCall Health API key. As mentioned earlier, this key can be used to access confidential patient data associated with your OnCall Health account and should be kept private at all times.

You'll also need Node.js installed on your computer. Visit this page for a list of operating system-specific installers.

Once you've downloaded the correct installer and run it, open Terminal on Mac (Windows Command Prompt on Windows), enter the following command, and hit enter.

node -v

You should see a response that looks something like this (the number may be different depending on which version of Node.js you downloaded).

v15.5.0

If you see an error, refer to this documentation for assistance.

Proceed once you've confirmed Node.js is installed on your computer.

Step 1: Create a new directory and navigate into it

Open Terminal on Mac (Windows Command Prompt on Windows) and navigate to whatever directory you'd like to build your Node.js application in.

Then, type the following command.

mkdir oncall-api-service

This will create the new folder you'll use to house your Node.js application's source code.

Once you've created the folder, navigate into it.

cd oncall-api-service

Step 2: Initialize npm in your directory

Enter the following command.

npm init

Terminal or Windows Command Prompt will now present you with a series of prompts. Your response to these prompts will influence the contents of your project's package.json file. You can read more about package.json files here.

Hit enter to accept the default value for each prompt until you arrive at this point:

entry point: (index.js)

Enter the following in Terminal or Windows Command Prompt when you arrive at that line. Then, hit enter.

app.js

Hit enter to accept the default values for the remaining prompts.

Step 3: Open your package.json and add the following line inside "scripts"

"start" : "node app.js",

Your package.json file should subsequently look like this.

{
  "name": "oncall-api-service",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

The line you've added tells Node.js to initialize using the directory's app.js file (which we'll create next) whenever you fire up your server.

Step 4: Create a file called "app.js" in your directory

This file will house the source code for your node.js application.

Open it and add the following line.

console.log("Hello world!");

Step 5: Return to Terminal or Windows Command Prompt

Type the following command.

npm start

You should see "Hello world!" in Terminal or Windows Command Prompt, which is a sign that everything is connected properly so far.

Step 6: Add the following dependencies to your project

Express.js

Express.js is a back end web development framework for Node.js. It's the component of your application that will make the server-side calls to OnCall Health's API. Install it using the following command in Terminal or Windows Command Prompt.

npm install express --save

CORS

CORS is middleware that will serve as a gatekeeper of requests to your Node.js application. Install it using the following command.

npm install cors --save

Request

Request is the package we'll use to redirect HTTPS requests from your Node.js application to OnCall Health's API. Install it using the following command.

npm install request --save

Dotenv

Dotenv is a package that allows you to set environment variables and make them accessible throughout your application. Install it using the following command.

npm install dotenv --save

Step 7: Open your app.js file

Delete everything inside the file and add the following lines of code at the top.

require("dotenv").config();
const express = require("express");
const app = express();
const request = require("request");
const cors = require("cors");

app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`App listening on port ${port}!`));

The first chunk of code stores the dependencies we added in Step 6 as variables (with the exception of Dotenv, which does not need to be stored as a variable).

The second chunk of code (after the line break) runs additional configuration for those dependencies based on their setup instructions.

The third chunk of code tells the application we're building to run on http://localhost:3000/ and display a message in Terminal or Windows Command Prompt confirming its status.

Step 8: Create a file called ".env" in the root directory of your project

Open the file and add the following two lines.

NODE_ENV=development
ONCALL_API_KEY=YOUR_API_KEY

Replace "YOUR_API_KEY" with your OnCall Health API key.

❗️

Important

If you plan on pushing this repository to GitHub, first ensure your .gitignore is configured to ignore your .env file. Otherwise, your OnCall Health API key will be accessible to anyone that can see your GitHub repository.

Step 9: Return to your app.js file and connect your Node.js application to OnCall Health's bulk Appointment retrieval endpoint

Add the following code to your app.js file.

app.use("/appointments", (req, res) => {
    request({
        method: "GET",
        uri: "https://api.oncallhealth.ca/appointments/",
        headers: {
            "Authorization" : `Token ${process.env.ONCALL_API_KEY}`,
            "Content-Type" : "application/json"
        }
    }).pipe(res);
});

📘

Note

If your development environment is based in the United States, your endpoint should start with https://api.oncallhealth.us/ rather than https://api.oncallhealth.ca/.

OnCall Health hosts separate servers in either country to ensure HIPAA and PHIPA compliance.

This block of code accomplishes a lot.

It tells your application that when a user lands on the /appointments URI of your Node.js application, a GET request should be made to the https://api.oncallhealth.ca/appointments/ endpoint. That GET request will contain the following headers:

  • Authorization with a value pointing to the ONCALL_API_KEY environment variable we set in Step 8
  • Content-Type with a value set to "application/json"

The second from last line of that code – the .pipe(res) bit – takes the OnCall Health API call's response and turns it into our server's response to this request.

Step 9.1: Test your Node.js application's connectivity to the bulk Appointment retrieval endpoint

Return to Terminal or Windows Command Prompt and entering the following command from your project's root directory.

npm start

If you open your browser and navigate to http://localhost:3000/appointments you should see a list of all Appointments associated with your API key.

If there aren't any appointments, the JSON object returned will look like this, which still indicates a successful response.

{
    "count": 0,
    "next": null,
    "previous": null,
    "results": []
}

Step 10: Return to your app.js file and connect your Node.js application to OnCall Health's Roster Contact creation endpoint

You can replicate Step 9 for any OnCall Health API endpoint that retrieves records in bulk.

But what about requests that require body parameters? Let's dive into that next, using the https://api.oncallhealth.ca/contacts/ endpoint, which creates a Roster Contact.

Add the following code to your app.js file.

app.use("/contacts", (req, res) => {
    request({
        method: "POST",
        uri: "https://api.oncallhealth.ca/contacts/",
        headers: {
            "Authorization" : `Token ${process.env.ONCALL_API_KEY}`,
            "Content-Type" : "application/json"
        },
        body: JSON.stringify(req.body)
    }).pipe(res);
});

This code looks very similar to what we added in Step 9. There are a few major differences, though:

  1. The method we're using to call OnCall Health's API is now POST, which corresponds with the method described in the API documentation for this endpoint.
  2. Underneath the headers, we now have a line that reads body: JSON.stringify(req.body). This line will extract body parameters from the request made to your server and use them when making the request to OnCall Health's API.

Step 10.1: Test your Node.js application's connection to the Roster Contact creation endpoint

Run the following command in your project's root directory.

npm start

Then, head to your browser and visit http://localhost:3000/contacts. You should see the following error message.

{
  "division":["This field is required."],
  "first_name":["This field is required."],
  "last_name":["This field is required."],
  "email":["This field is required."],
  "sex":["This field is required."]
}

This confirms your Express.js application has connected to the OnCall Health API endpoint. The error message simply points out that your request lacks the required body parameters.

This is to be expected since we didn't add any parameters when we visited http://localhost:3000/contacts. In fact, we can't add parameters through simple browser requests. We can add these body parameters using cURL from Terminal or Windows Command Prompt, however.

Open whichever command line tool is applicable and prepare a cURL request that looks like this.

curl --header "Content-Type: application/json" \
--request POST \
--data '{"division":"YOUR_DIVISION_URL","provider":"YOUR_PROVIDER_URL","first_name":"DESIRED_FIRST_NAME","last_name":"DESIRED_LAST_NAME","email":"DESIRED_EMAIL","sex":"DESIRED_SEX"'} \
http://localhost:3000/contacts/

The data line should be adjusted to contain your intended inputs. For example, replace "YOUR_DIVISION_URL" with your OnCall Health division URL (contact your Customer Service Manager if you don't know what division URL to use).

If you've done everything correctly, you'll see a successful response resembling this (but with data matching your inputs).

{
    "id":316792,
    "division":"YOUR_DIVISION_URL",
    "provider":"YOUR_PROVIDER_URL",
    "url":"https://api.oncallhealth.ca/contacts/123/",
    "name":"John Doe",
    "first_name":"John",
    "last_name":"Doe",
    "email":"[email protected]",
    "phone":null,
    "notes":null,
    "sex":"male",
    "date_of_birth":null,
    "appointments":"https://api.oncallhealth.ca/contacts/123/appointments/",
    "custom_field_names":{},
    "custom_field_values":{}
}

Next steps

Your app.js file should currently look like this.

require("dotenv").config();
const express = require("express");
const app = express();
const request = require("request");
const cors = require("cors");

app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`App listening on port ${port}!`));

app.use("/appointments", (req, res) => {
    request({
        method: "GET",
        uri: "https://api.oncallhealth.ca/appointments/",
        headers: {
            "Authorization" : `Token ${process.env.ONCALL_API_KEY}`,
            "Content-Type" : "application/json"
        }
    }).pipe(res);
});

app.use("/contacts", (req, res) => {
    request({
        method: "POST",
        uri: "https://api.oncallhealth.ca/contacts/",
        headers: {
            "Authorization" : `Token ${process.env.ONCALL_API_KEY}`,
            "Content-Type" : "application/json"
        },
        body: JSON.stringify(req.body)
    }).pipe(res);
});

Here are some ideas regarding what to do next.

Add connectivity for more endpoints

If you understand the steps we've outlined in this guide, you now have the knowledge required to connect your Node.js application with other OnCall Health API endpoints. Check out our documentation here for a full list of endpoints available through OnCall Health's API.

Deploy your Node.js application

Currently, your Node.js application only runs on localhost. If you want it to be accessible from other networks, you'll need to deploy it using a tool such as Heroku. Find deployment instructions here.

The sky's the limit – happy building!