0

Create async request for an analytics report using a template

by
Published Dec 20, 2024

This takes a template ID and an optional custom timeframe and constructs an asynchronous report based on the template. It returns a token that you can use to download the report when it is ready.

Script pinterest Verified

The script

Submitted by hugo697 Bun
Verified 536 days ago
1
//native
2
type Pinterest = {
3
  token: string;
4
};
5
/**
6
 * Create async request for an analytics report using a template
7
 * This takes a template ID and an optional custom timeframe and constructs an asynchronous report based on the
8
template. It returns a token that you can use to download the report when it is ready.
9
 */
10
export async function main(
11
  auth: Pinterest,
12
  ad_account_id: string,
13
  template_id: string,
14
  start_date: string | undefined,
15
  end_date: string | undefined,
16
  granularity: "TOTAL" | "DAY" | "HOUR" | "WEEK" | "MONTH" | undefined,
17
) {
18
  const url = new URL(
19
    `https://api.pinterest.com/v5/ad_accounts/${ad_account_id}/templates/${template_id}/reports`,
20
  );
21
  for (const [k, v] of [
22
    ["start_date", start_date],
23
    ["end_date", end_date],
24
    ["granularity", granularity],
25
  ]) {
26
    if (v !== undefined && v !== "" && k !== undefined) {
27
      url.searchParams.append(k, v);
28
    }
29
  }
30
  const response = await fetch(url, {
31
    method: "POST",
32
    headers: {
33
      Authorization: "Bearer " + auth.token,
34
    },
35
    body: undefined,
36
  });
37
  if (!response.ok) {
38
    const text = await response.text();
39
    throw new Error(`${response.status} ${text}`);
40
  }
41
  return await response.json();
42
}
43