Graphing COVID time series data using Chart.js and Postman
Tags: data, api, datavisualization, postman
Published: 2020-04-06 21:25:38

---
title: Graphing COVID time series data using Chart.js and Postman
published: true
date: 2020-03-31 05:57:07 UTC
tags: data,api,data-visualization,postman
canonical_url: https://medium.com/@joycelin.codes/graphing-covid-time-series-data-using-chart-js-and-postman-5d13eff44761
cover_image: https://cdn-images-1.medium.com/max/1024/1*aVJ8kRX3wSgMWy9Pl4gquQ.jpeg
description: Learn to visualize API and other data using Postman’s visualizer

---

The Postman team has been hard at work creating a [COVID-19 API Resource Center](https://covid-19-apis.postman.com/) to give people easier access to public data. People in the broader community have come together to share and contribute to data in a variety of ways.

Let’s take one API and build a data visualization, from the ground up.

> 🧡 Shout out to the open-source contributors who made this data accessible — the API used in this example is from [this other collection](https://explore.postman.com/templates/6495/covidapi) using [this dataset](https://github.com/CSSEGISandData/COVID-19) converted [here](https://github.com/pomber/covid19) and hosted on [this API](https://covidapi.info/).

### Learn to visualize data in Postman

In this tutorial, we will learn how to use [the Postman visualizer](https://learning.postman.com/docs/postman/sending-api-requests/visualizer/) to graph time series data within the Postman app. It will help if you already know a bit of JavaScript, HTML, and CSS, or can follow along.

#### Follow along

To follow along with these, and other, examples, click the orange **+New** button in the top left of the Postman app. Under the [Templates](https://www.getpostman.com/docs/v6/postman/launching_postman/newbutton#templates) tab, search for **How to visualize data in Postman,** and import the sample collection into your instance of the Postman app.

Walk through step-by-step documentation for [this sample collection](https://explore.postman.com/templates/6713/how-to-visualize-data-in-postman) in the Postman app or [on the web](https://documenter.getpostman.com/view/1215211/SzYW4g6t?version=latest).

Don’t feel like reading? Watch the [video series](https://www.youtube.com/playlist?list=PL6yYBvW22vbqiyhb_U-RWfxuZNv0DKBP8) instead.

{% youtube KTmeZ5cSVSg %}

Let’s get started!

#### Step 1: scripts in Postman

Under the **Pre-request Script** and **Tests** tabs, you can add JavaScript code before the request is sent and after the response is received, respectively. Postman will run this code in the [Postman Sandbox](https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference) environment, which also gives you access to some in-built functions that we’ll explore in a bit. This code that runs before or after your request is called a [script in Postman](https://learning.postman.com/docs/postman/scripts/intro-to-scripts/).

- **Pre-request Script**  — before request is sent
- **Test Script**  — after response is received

Open the [Postman console](https://learning.postman.com/docs/postman/sending-api-requests/debugging-and-logs/#network-calls-with-the-postman-console) using the bottom left icon. **Send** this request, and see the execution order of your main network request in relation to the pre-request and test scripts.

![](https://cdn-images-1.medium.com/max/1024/1*hFFt1XAznxFwABv7-Hz14w.png)<figcaption>execution order for pre-request and test scripts in the Postman Console</figcaption>

#### Step 2: add the visualizer

Let’s use the Postman docs to learn [how to visualize our response data](https://learning.postman.com/docs/postman/sending-api-requests/visualizer/). Under the **Tests** tab, add this code to set the visualizer.

```
// Set visualizer
pm.visualizer.set(template, {
    // Pass the response body parsed as JSON as `data`
    response: pm.response.json()
});
```

The [**`pm object`**](https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference/#pm) contains a bunch of information and functions related to the script being executed. It’s available in the [Postman Sandbox](https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference) that we talked about in the previous step.

In this example, we’re using the `pm.visualizer.set()` method to apply the visualizer code that we will write in the next step, and then display it in the **Visualize** tab of our response after we run the request. This method takes three parameters.

![](https://cdn-images-1.medium.com/max/954/1*1t4ZOS39eDDUgKw9GWONSw.png)<figcaption>pm.visualizer.set() method accepts three parameters</figcaption>

Let’s dig into these parameters in the next steps.

Don’t hit Send yet!

#### Step 3: add the layout

Now that we’ve added `pm.visualizer.set()` under the **Tests** tab, take a look at the first (and only required) parameter.

> `layout` - (required) an HTML template string of the front-end view we want to render

In our example code, we see a placeholder `template` as the first parameter in `pm.visualizer.set()`. We haven't initialized that variable yet. Above this code, add a variable called `template` as an empty string.

```
let template = ``;

// Set visualizer
pm.visualizer.set(template, {
    // Pass the response body parsed as JSON as `data`
    response: pm.response.json()
});
```

Inside the template string, add some HTML elements like header, text, or an image.

Hit **Send** , and take a look at the **Visualize** tab of our response after we run the request. You should see something like this.

![](https://cdn-images-1.medium.com/max/1024/1*AnU3giclqAPDYS9GWgGjrg.png)<figcaption>render HTML using the visualizer</figcaption>

This is good, but we haven’t passed any data to our template yet. Let’s forge ahead!

#### Step 4: pass the data

Now that we’ve added `pm.visualizer.set()` and defined an initial layout for our front-end view, let's take a look at the second parameter.

> `data` - (optional) data object that you can bind to the template; the properties of this object can be accessed in the template

In our example code, we see a placeholder for the second parameter in `pm.visualizer.set()`. Once again, we are using the [`pm object`](https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference/#pm) in the [Postman Sandbox](https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference). This time, `pm.response.json()` captures the response returned from the API so we can parse the response body as JSON.

```
pm.visualizer.set(template, {
    // Pass the response body parsed as JSON as `data`
    response: pm.response.json()
});
```

In the string template where we define our front-end layout, the [Handlebars](https://handlebarsjs.com/) templating engine is built in to help us render the data returned from our API. Use the double curly braces to wrap a Handlebars expression like `{{expression}}`.

This is what our data looks like coming back from our API.

![](https://cdn-images-1.medium.com/max/1024/1*i7Tdeoy7qkguz7jz-1nXbQ.png)<figcaption>how the JSON response data is structured</figcaption>

For this example, use Handlebars [`each`](https://handlebarsjs.com/guide/builtin-helpers.html#each) in our template string to loop through each item of the response body. We are looping through `response.result` because response is the property name we used in `pm.visualizer.set()` and `result` is the property name from the response body returned from our API. Use Handlebars `{{@key}}` to reference the current key name, which will be a date. And then add an HTML line break tag `<br>` to list each date on a new line.

```
let template = `
    {{#each response.result}}
        {{@key}} <br>
    {{/each}}
`;
```

Hit **Send** , and take a look at the **Visualize** tab of our response. You should see something like this.

![](https://cdn-images-1.medium.com/max/1024/1*x2ZcLtMcBp1XiARsEBSTaQ.png)<figcaption>use Handlebars.js to loop through the response and render the keys</figcaption>

This is progress, but if you’re a front-end developer or designer, you’re probably thinking — oh how ugly! Let’s keep going.

#### Step 5: make it pretty

We have a functioning visualization, but it’s not very pretty and it’s not very useful yet. So far, we’ve added a tiny bit of JavaScript and HTML to our layout template. There’s a couple more steps we could take to really polish it up.

- Add more HTML
- Add CSS using `<style>` tags or `<link>` to external stylesheets from within your template
- Add JavaScript interactions or external libraries using `<script>` tags inside your template

Let’s go ahead and add some HTML and CSS to our template string. In this example, I added paragraph tags `<p>`, and then CSS within `<style>` tags to style those paragraph elements. Hit **Send** , and see how our visualization has changed.

![](https://cdn-images-1.medium.com/max/1024/1*1dD6GYLr1sZKtopI2DO3cg.png)<figcaption>add HTML and CSS to style the layout</figcaption>

Do you feel pretty?

Right-click on the visualization, and select **Inspect visualization** to open **Developer Tools**. In this new window, you can inspect elements in your HTML visualization, log console statements from within the defined template, and dig deeper into what’s going on.

Under the **Elements** tab of the Developer Tools, select an HTML element and update the CSS under the **Styles** tab to see real-time updates to the HTML rendered under the **Visualize** tab in Postman.

![](https://cdn-images-1.medium.com/max/1024/1*mRVDmSxrBOFngxEeZS8YXA.png)<figcaption>Developer Tools to inspect your visualization</figcaption>

Neat, huh? Let’s try adding more JavaScript next.

#### Step 6: make a line graph

We just learned how to style our visualization using HTML and CSS. Now, let’s add some more JavaScript to add interactions or external libraries using `<script>` tags inside our template.

If we revisit the data returned from our API, it would definitely be more interesting to visualize data over time, instead of this lovely but meaningless list of dates.

![](https://cdn-images-1.medium.com/max/1024/1*i7Tdeoy7qkguz7jz-1nXbQ.png)<figcaption>remember, this is how our JSON response data is structured</figcaption>

To do this, we’ll use the [Chart.js](https://www.chartjs.org/) library to make a line graph. Let’s take a look at their [getting started documentation](https://www.chartjs.org/docs/latest/getting-started/).

> First, we need to have a canvas in our page. Replace the current code in your template string with this HTML element.

```
<canvas id="myChart"></canvas>
```

> Now that we have a canvas we can use, we need to include Chart.js in our page. Add this script to the beginning part of your template string.

```
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
```

> Now, we can create a chart. Add this script after your `<canvas>` element within your template string. Don’t forget to surround this code block with an opening and closing `<script>` tag.

```
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'My First dataset',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
        }]
    },

    // Configuration options go here
    options: {}
});
```

If you hit **Send** now, you can see a line chart under the **Visualize** tab that displays the data hardcoded in the boilerplate snippet. In Step 4, we learned how to pass the data from `pm.visualizer.set()` to access the data within our HTML template using the Handlebars double curly braces. If we want to access this data from within a JavaScript `<script>`, we can use `pm.getData(callback)`.

The `pm.getData(callback)` method takes a callback function as its parameter. This callback method accepts two parameters: `error` and `data`. The second parameter is the data that was passed through `pm.visualizer.set()`. Wrap this bit of code around the boilerplate snippet (still inside the `<script>` tags).

```
pm.getData( function (error, data) {
    <! Boilerplate JS to execute using the data passed through from `pm.visualizer.set()` ---->
}
```

Now we have access to the data passed through from `pm.visualizer.set()`. In the boilerplate, we need to update `labels` for our data, as well as `label` and `data` for our datasets. Once again, we will parse the information passed through from `pm.visualizer.set()`.

Chart.js expects the `labels` for our data and the `data` for our dataset to be formatted as arrays. So the label would be a date like `"2020-01-22"`, and the data for the dataset would be the corresponding value for that date.

Update the array for the `labels` of our data. Here we are turning an object `data.response.result` into an array using `Object.entries()`, and then mapping each item in that array to return another array of the first property of each item. See if you can update `label` and `data` for our datasets on your own.

```
...
labels: Object.entries(data.response.result).map( (item) => item[0]),
...
```

Hit **Send** , and see the time series data for COVID cases under the **Visualize** tab of the response.

![](https://cdn-images-1.medium.com/max/1024/1*DHhYaM-crW_ev_x3abAdWw.png)<figcaption>use Chart.js to render time series data</figcaption>

### Final thoughts

This was a simple example with an easy-to-use API and a straight forward charting library. Just knowing the basics allows you to better understand the data, stay informed, and help others.

![](https://cdn-images-1.medium.com/max/1024/1*YrWv1YwhYwZ04tceaKmFGw.png)

![](https://cdn-images-1.medium.com/max/1024/1*DHhYaM-crW_ev_x3abAdWw.png)<figcaption>compare the slopes between two countries</figcaption>

Take a look at the rest of the example collection to continue exploring some enhancements, as well as tips for troubleshooting.

Ideas for next steps to enhance this visualization:

- Display time series data for another value
- Display time series data for a different country
- Turn the country’s ISO in the URL and chart label into a variable
- Style the chart with the country’s flag colors
- Make it even prettier with CSS, Handlebars, Chart.js, or other libraries
- Compare two different countries within the same graph
- Visualize data from an external file

Do you have other ideas? Check out Postman’s [COVID-19 API Resource Center](https://covid-19-apis.postman.com/) for more interesting data, and let us know if you build something neat!