Skip to content

Commit 8d03af3

Browse files
authored
feat(docs): add reports api guide
1 parent 2974fd0 commit 8d03af3

File tree

6 files changed

+271
-5
lines changed

6 files changed

+271
-5
lines changed

src/pages/guides/api-guides/customer-chat-api-guide/index.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ tagline: "Learn how to build a chat app using the Customer Chat API in practice.
77
desc: "Follow a step-by-step guide to build a functional application sending messages to chat through the Customer Chat API."
88
---
99

10-
# Introduction
10+
## Introduction
1111

1212
In this guide, we will create a simple web chat application from scratch using HTML, CSS, and Vanilla JavaScript to integrate with the [Customer Chat Web API](https://platform.text.com/docs/messaging/customer-chat-api).
1313

src/pages/guides/api-guides/index.mdx

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,11 @@ Learn how to connect to the Customer Chat API and build a simple message-based a
2020
<SectionLink to={"/guides/api-guides/customer-chat-api-guide"}>
2121
Go to guide
2222
</SectionLink>
23+
24+
### Fetching data from the Reports API
25+
26+
Learn how to connect to the Reports API to fetch analytics data and use it in Google Sheets or BI tools like Looker Studio and Tableau Cloud.
27+
28+
<SectionLink to={"/guides/api-guides/reports-api-guide"}>
29+
Go to guide
30+
</SectionLink>
Lines changed: 258 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,258 @@
1+
---
2+
weight: 25
3+
category: "guides"
4+
subcategory: "api-guides"
5+
title: "Reports API guide"
6+
tagline: "Learn how to fetch reports from the Reports API."
7+
desc: "Step through a practical example of using the Reports API to retrieve analytics data and customize metrics."
8+
---
9+
10+
## Introduction
11+
12+
The [Reports API](https://platform.text.com/docs/data-reporting) lets you extract analytics and historical data from LiveChat, such as chat statistics, agent performance metrics, and trends. This is useful when creating custom reports, building dashboards, or integrating data with external tools. The API gives you raw access to the data to analyze it your way.
13+
14+
## When to use the Reports API
15+
16+
Use the Reports API in scenarios where you need to programmatically retrieve LiveChat reports data for analysis or integration. For example:
17+
18+
* **Export data for ad-hoc analysis**: You can pull chat metrics (like total chats, first response time, chat ratings) on demand and load them into a spreadsheet or application for deeper analysis.
19+
* **Automate regular reporting**: You can script automatic data pulls if you need to generate recurring reports (daily, weekly, monthly) or send scheduled updates.
20+
* **Integrate with BI tools and databases**: The API lets you merge LiveChat data with data from other sources. For instance, you can feed LiveChat stats into Google Sheets, Tableau, or Looker Studio to build unified dashboards.
21+
22+
In short, use the Reports API whenever you need direct, flexible access to LiveChat’s reporting data outside of the standard UI for custom analysis or integration.
23+
24+
## What this guide covers
25+
26+
This guide will walk through:
27+
28+
* Authenticating with the Reports API using a Personal Access Token.
29+
* Ad-hoc and automated data retrieval into Google Sheets through a Google Apps Script.
30+
* Connect the API to Business Intelligence tools like Tableau Cloud and Looker Studio.
31+
32+
## Prerequisites
33+
34+
Before you begin, make sure you have the following:
35+
36+
* [LiveChat account](https://www.livechat.com/) with reporting access (Team plan or higher). Ensure you can access the data you want to pull from the API.
37+
* [Developer Console account](https://platform.text.com/console), where you will create and configure your Personal Access Token.
38+
* Basic familiarity with JSON and CSV.
39+
* An account in the service you want to store the pulled data in (Google, Tableau, or Looker).
40+
41+
## Personal Access Token authentication
42+
43+
Before pulling any data, you need to authenticate with the API. The goal is to do this automatically (so a script or tool can run without interactive login). The simple approach we will use in this guide is a Personal Access Token (PAT), which will serve as our API access.
44+
45+
To generate your PAT, in the [Developer Console](https://platform.text.com/console/settings/authorization/personal-access-tokens), navigate to **Settings > Authorization > Personal Access Tokens**. Create a new token with the scopes needed for the Reports API endpoints you want to pull — information about those is in the [documentation](https://platform.text.com/docs/data-reporting/reports-api) for each endpoint. For instance, the [Total Chats](https://platform.text.com/docs/data-reporting/reports-api#total-chats) endpoint requires the `reports_read` scope.
46+
47+
After creating your token, copy the token value, your Account ID, and the Base64 encoded token as well — you won’t be able to view any of these again after closing the page. Save those in a secure location.
48+
49+
Treat your PAT like a password. Do not expose it in client-side code or share it publicly. Avoid hard-coding the token in the code when writing scripts like Google Apps Script. Use secure storage or environment variables where possible, for example, in Google Apps Script, those would be script properties.
50+
51+
### Base64 token encoding
52+
53+
Scripts and external tools often require you to parse the token into a Base64 format, where the Account ID is combined with your Personal Access Token into one value. The result is what you use in the HTTP Authorization header as **Basic** Authentication.
54+
55+
If you encode those to Base64 through an online encoder, encode the string exactly as `<account_id>:<pat>` with no extra characters. The Developer Console already returns this value after creating your token, so you can use it out of the box.
56+
57+
## Ad-hoc data retrieval to Google Sheets
58+
59+
One of the quickest ways to analyze LiveChat data is to pull it into [Google Sheets](https://docs.google.com/spreadsheets/). In a spreadsheet, you can filter, pivot, and visualize the data ad hoc.
60+
61+
Before you start, create an empty Google Sheet to hold your data.
62+
63+
### Apps Script
64+
65+
Google Apps Script allows you to use JavaScript to manipulate your spreadsheet and call external APIs. We can write a custom function to fetch data from the Reports API.
66+
67+
To open the script editor, go to **Extensions > Apps Script** in your created sheet. There, you can write a function to fetch the data.
68+
69+
Before you paste the script, add your Personal Access Token as a script property. To do this, in your open editor, navigate to **Project Settings > Script Properties** and add a property named `base64token` with your encoded token as the value. Save the script properties and return to the editor.
70+
71+
Below is a ready-to-use script that allows you to customize the data range, the Reports API endpoints you call, and column header names.
72+
73+
<CodeSample path={'Reports API Google Apps Script code'}>
74+
75+
```js
76+
function pullLiveChatReportData() {
77+
// Config
78+
const SHEET_NAME = 'LiveChat report';
79+
const DAYS_BACK = 30; // how many days back (including today)
80+
const METRIC_MAP = {
81+
'Date': '__DATE__',
82+
'Average response time (s)':'chats/response_time.response_time',
83+
'Chatting duration':'chats/duration.agents_chatting_duration',
84+
'Chat count':'chats/total_chats.total',
85+
'Agent hours':'agents/availability.hours',
86+
'Bad rates':'chats/ratings.bad'
87+
};
88+
89+
// Authorization
90+
const props = PropertiesService.getScriptProperties();
91+
const BASIC_AUTH = props.getProperty('base64token'); // base64 of "accountId:PAT"
92+
if (!BASIC_AUTH) throw new Error('Add token to Script properties.');
93+
const headers = { 'Authorization': 'Basic ' + BASIC_AUTH, 'Content-Type': 'application/json' };
94+
95+
// Dates
96+
const today = new Date();
97+
const from = new Date(today);
98+
from.setDate(from.getDate() - (DAYS_BACK - 1));
99+
const fromISO = isoDay(from, '00:00:00Z');
100+
const toISO = isoDay(today, '23:59:59Z');
101+
const allDates = listDates(from, today); // ['YYYY-MM-DD', ...]
102+
103+
// Build metric requests (works only date-keyed endpoints)
104+
const base = 'https://api.livechatinc.com/v3.6/reports/';
105+
const metrics = Object.entries(METRIC_MAP)
106+
.filter(([_, path]) => path !== '__DATE__')
107+
.map(([col, path]) => {
108+
const [endpoint, ...pathParts] = path.split('.');
109+
return { col, endpoint, pathParts };
110+
});
111+
112+
// Fetch each endpoint
113+
const body = JSON.stringify({ distribution: 'day', filters: { from: fromISO, to: toISO } });
114+
const byMetric = {}; // col -> { 'YYYY-MM-DD': value }
115+
metrics.forEach(m => {
116+
try {
117+
const resp = UrlFetchApp.fetch(base + m.endpoint, {
118+
method: 'post', headers, payload: body, muteHttpExceptions: true
119+
});
120+
if (resp.getResponseCode() !== 200) return;
121+
const json = JSON.parse(resp.getContentText());
122+
const recs = (json && json.records) ? json.records : {};
123+
byMetric[m.col] = {};
124+
Object.keys(recs).forEach(date => {
125+
let v = recs[date];
126+
for (const k of m.pathParts) { if (v && typeof v === 'object') v = v[k]; else { v = undefined; break; } }
127+
if (v !== undefined) byMetric[m.col][date] = v;
128+
});
129+
} catch (e) {
130+
// skip on error; keep going
131+
}
132+
});
133+
134+
// Build table
135+
const headersRow = Object.keys(METRIC_MAP);
136+
const rows = allDates.map(d => headersRow.map(h => {
137+
if (METRIC_MAP[h] === '__DATE__') return d;
138+
const m = byMetric[h];
139+
return (m && m[d] !== undefined) ? m[d] : '';
140+
}));
141+
142+
// Write sheet
143+
const ss = SpreadsheetApp.getActive();
144+
const sh = ss.getSheetByName(SHEET_NAME) || ss.insertSheet(SHEET_NAME);
145+
sh.clearContents();
146+
sh.getRange(1, 1, 1, headersRow.length).setValues([headersRow]);
147+
if (rows.length) sh.getRange(2, 1, rows.length, headersRow.length).setValues(rows);
148+
sh.setFrozenRows(1);
149+
sh.autoResizeColumns(1, headersRow.length);
150+
151+
// Helpers
152+
function isoDay(d, tail) {
153+
const yyyy_mm_dd = new Date(d.getTime() - d.getTimezoneOffset()*60000).toISOString().slice(0,10);
154+
return `${yyyy_mm_dd}T${tail}`;
155+
}
156+
function listDates(start, end) {
157+
const out = [];
158+
const cur = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate()));
159+
const stop = new Date(Date.UTC(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate()));
160+
while (cur <= stop) {
161+
const y = cur.getUTCFullYear(), m = String(cur.getUTCMonth()+1).padStart(2,'0'), d = String(cur.getUTCDate()).padStart(2,'0');
162+
out.push(`${y}-${m}-${d}`);
163+
cur.setUTCDate(cur.getUTCDate() + 1);
164+
}
165+
return out;
166+
}
167+
}
168+
```
169+
170+
</CodeSample>
171+
172+
After adding this script, save it. You can test it by running the `pullLiveChatReportData` function in the Apps Script editor. Then check your Google Sheet — you should see your headers and 30 rows of data.
173+
174+
### Script breakdown
175+
176+
Let’s break down what this script does, step by step:
177+
178+
* First, the script defines some configuration values at the top. It sets the sheet name, the number of days to go back, and a metric mapping object. This mapping links editable column names to their respective API endpoints and JSON paths.
179+
* Then, it retrieves a Base64-encoded token for Basic Auth from the script properties (`base64token`). The script then prepares an HTTP header with this token for the Authorization. If the token isn’t found, it throws an error.
180+
* The script then calculates the date range for the past 30 days (including today). It creates a start date (from) 29 days before today and an end date (today). These are formatted as ISO timestamp strings (for example, `YYYY-MM-DDT00:00:00Z` for the start of the day and `YYYY-MM-DDT23:59:59Z` for the end of the day) because the API expects timestamps in that format. It also generates a list of all dates in between using a helper function, so we have every date from the start to the end.
181+
* For each metric in the `METRIC_MAP` (except the `__DATE__` placeholder), the script determines which API endpoint to call and how to navigate the JSON to get the value. It builds a request body (as JSON) with the date filters. and sets the data distribution by `day` so that the API returns data grouped by day within that range.
182+
* The script loops through each metric’s endpoint and makes a POST request to the Reports API for that metric. It extracts the specific metric value for each date from the response (following the path defined in `METRIC_MAP`) and stores these values in an object (`byMetric`) keyed by date for each metric name. If a request fails or an error occurs, the script skips that metric without stopping the whole process.
183+
* After fetching all metrics, the script prepares the data to write into the Google Sheet. It first creates a header row using the keys from `METRIC_MAP` (in our code example, `Date`, `Average response time (s)`, etc.). Then it iterates over each date in the range (the list of dates it generated). For each date, a row of values is created: the date itself and the values for each metric on that date. If a particular metric has no data for a given date, it leaves an empty cell for that.
184+
* Finally, the script gets the Google Sheet by name (in the example, it’s “LiveChat report”). It clears any existing content in that sheet, then writes the header row to the first row. It then writes all the rows of data (if any) starting from the second row. It also freezes the header row and auto-resizes the columns.
185+
* The script includes two helper functions at the bottom: `isoDay(d, tail)`, which takes a JavaScript `Date` object `d` and a time string `tail` (like `00:00:00Z`), and returns a date-time string in ISO format (UTC) with that time. It’s used to format the start and end timestamps for the API query (beginning of the first day and end of the last day). `listDates(start, end)` helper generates an array of date strings in `YYYY-MM-DD` format for every day between the start date and end date (inclusive). The script uses this to know all the dates it should expect data for, so it can output a row for each date, even if some metrics have no data on a particular day.
186+
187+
#### Changing endpoints
188+
189+
The script is designed so you can easily adjust which metrics are pulled from the Reports API. This is controlled through the `METRIC_MAP`.
190+
191+
The `METRIC_MAP` is essentially a dictionary that maps:
192+
193+
* Keys (left side): the column headers you want to see in your Google Sheet (like “Chat count" or "Agent hours").
194+
* Values (right side): instructions on where to fetch the data. Each value has two parts:
195+
* **Endpoint name** — tells the script which API endpoint to call. Example: `chats/total_chats` corresponds to the `/reports/chats/total_chats` endpoint.
196+
* **Field path** — tells the script which property inside the endpoint’s JSON response to extract. Example: `.total` means “take the value of the `total` field from each daily record.”
197+
198+
Let’s look at the [Total Chats](https://platform.text.com/docs/data-reporting/reports-api#total-chats) endpoint as an example:
199+
200+
```json
201+
'Chat count': 'chats/total_chats.total'
202+
```
203+
204+
* `chats/total_chats` - the API endpoint to call (`/reports/chats/total_chats`)
205+
* `.total` - the field in each daily record to extract
206+
207+
If you want to add an endpoint to the report or modify the pulled property, in the example of Total Chats, the endpoint also returns information about `continuous` chats. To access this data, you would extend the `METRIC_MAP` with:
208+
209+
```json
210+
'Continuous chat count': 'chats/total_chats.continuous'
211+
```
212+
213+
This pattern repeats for any date-keyed properties. Identify the endpoint (like `chats/response_time`), inspect its response fields in the docs, and add entries to `METRIC_MAP` with the endpoint name and the field path separated by dots.
214+
215+
#### Changing the data range
216+
217+
To change the data range pulled by the script, simply edit the number in the `DAYS_BACK` value:
218+
219+
```javascript
220+
const DAYS_BACK = 30; // how many days back (including today)
221+
```
222+
223+
### Setting a trigger
224+
225+
You can set an automatic trigger to update the data in your Sheet under specific conditions or on a specific schedule. To do that, go to **Triggers** in the Apps Script editor and create a new trigger for the `pullLiveChatReportData` function.
226+
227+
You can schedule it to run nightly, every X hours, etc. Google Apps Script triggers allow time-based execution; you could also use an on-open trigger to fetch fresh data whenever the sheet is opened.
228+
229+
### Automated no-code options
230+
231+
If you’re not comfortable writing script code, there are no-code solutions to get LiveChat API data into Google Sheets. These typically involve using a connector add-on or an automation service.
232+
233+
One option is Google Sheets API add-ons like API Connector (by Mixed Analytics) or Apipheny (by Apipheny.io), where you can configure API calls via a simple interface in Google Sheets. You can also use services like Zapier to connect LiveChat data to Google Sheets.
234+
235+
## Connecting the Sheet to Looker
236+
237+
You can easily connect the above-created sheet to [Looker Studio](https://lookerstudio.google.com/) to get a visualization of your pulled data. To do that:
238+
239+
1. Open **Looker Studio > Reports** and create a new report.
240+
2. From the available Google Connectors, choose Google Sheets.
241+
3. In there, find and select your sheet — in our case, the file is named “API report”. Choose the appropriate worksheet (if you have more than one), and click **Add** to connect it with your report.
242+
243+
That’s it! On the right-hand side navigation, you’ll find a **Data** menu. From there, you’ll be able to see and access information from your sheet and organize it in your Looker report.
244+
245+
## Connecting to Tableau
246+
247+
The same connection method applies to [Tableau](https://dub01.online.tableau.com/) — you can link the created Google Sheet with a Tableau Cloud Workbook:
248+
249+
1. Open Tableau Cloud and navigate to **New > Virtual Connection**.
250+
2. Select Google Drive from the available connectors and authorize the connection.
251+
3. Find and select the sheet that holds your data, then click **Connect**.
252+
4. Publish the connection by clicking the **Publish** button, after which you can assign it to a project.
253+
254+
That’s done. You can now assign this connection to a workbook in Tableau and access your report data.
255+
256+
---
257+
258+
You can extend the setup from here to fit your team’s needs. For example, you might add additional endpoints to your `METRIC_MAP`, adjust the reporting window, or schedule updates more frequently. With this foundation, you can move beyond the default in-app reports and design a reporting workflow that scales with your business.

0 commit comments

Comments
 (0)