0

Query Data Source

by
Published Apr 16, 2024

Query the rows of a database's data source, with optional filter and sorts.

Script notion Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 3 hours ago
1
//native
2

3
export type DynSelect_data_source_id = string
4

5
export async function data_source_id(auth: RT.Notion) {
6
  const response = await fetch("https://api.notion.com/v1/search", {
7
    method: "POST",
8
    headers: {
9
      Authorization: `Bearer ${auth.token}`,
10
      "Content-Type": "application/json",
11
      Accept: "application/json",
12
      "Notion-Version": "2026-03-11",
13
    },
14
    body: JSON.stringify({
15
      filter: { property: "object", value: "data_source" },
16
    }),
17
  })
18
  if (!response.ok) {
19
    throw new Error(`${response.status} ${await response.text()}`)
20
  }
21
  const { results } = (await response.json()) as {
22
    results: { id: string; title: { plain_text: string }[] }[]
23
  }
24
  return results.map((d) => ({
25
    value: d.id,
26
    label: d.title.map((t) => t.plain_text).join("") || d.id,
27
  }))
28
}
29

30
/**
31
 * Query Data Source
32
 * Query the rows (pages) of a database's data source, with optional filter and sorts. The filter is a Notion filter object, e.g. {"property": "Status", "status": {"equals": "Done"}}. Paginate with `next_cursor` as `start_cursor`.
33
 */
34
export async function main(
35
  auth: RT.Notion,
36
  data_source_id: DynSelect_data_source_id,
37
  filter: { [key: string]: any } | undefined,
38
  sorts: { [key: string]: any }[] | undefined,
39
  start_cursor: string | undefined,
40
  page_size: number | undefined
41
) {
42
  const body: { [key: string]: any } = {}
43
  if (filter && Object.keys(filter).length) body.filter = filter
44
  if (sorts?.length) body.sorts = sorts
45
  if (start_cursor !== undefined && start_cursor !== "") {
46
    body.start_cursor = start_cursor
47
  }
48
  if (page_size !== undefined) body.page_size = page_size
49

50
  const response = await fetch(
51
    `https://api.notion.com/v1/data_sources/${data_source_id}/query`,
52
    {
53
      method: "POST",
54
      headers: {
55
        Authorization: `Bearer ${auth.token}`,
56
        "Content-Type": "application/json",
57
        Accept: "application/json",
58
        "Notion-Version": "2026-03-11",
59
      },
60
      body: JSON.stringify(body),
61
    }
62
  )
63

64
  if (!response.ok) {
65
    throw new Error(`${response.status} ${await response.text()}`)
66
  }
67

68
  return await response.json()
69
}
70

Other submissions
  • Submitted by henri186 Bun
    Created 514 days ago
    1
    // Define the Notion resource type as required for the function
    2
    type Notion = {
    3
      token: string
    4
    }
    5
    
    
    6
    export async function main(notion: Notion, databaseId: string): Promise<any> {
    7
      // The URL for fetching data from a Notion database should be replaced with the actual database URL
    8
      const databaseUrl = `https://api.notion.com/v1/databases/${databaseId}/query`;
    9
    
    
    10
      // Set up the request headers
    11
      const headers = {
    12
        'Authorization': `Bearer ${notion.token}`,
    13
        'Notion-Version': '2022-06-28', // Use the latest version supported by your integration
    14
        'Content-Type': 'application/json'
    15
      };
    16
    
    
    17
      // Perform the fetch request to get data from the Notion database
    18
      try {
    19
        const response = await fetch(databaseUrl, {
    20
          method: 'POST', // The Notion API requires a POST request to query a database
    21
          headers: headers,
    22
          body: JSON.stringify({}) // You can customize the body according to the Notion API documentation for filtering, sorting, etc.
    23
        });
    24
    
    
    25
        // Check if the request was successful
    26
        if (!response.ok) {
    27
          throw new Error(`Failed to fetch Notion database: ${response.status} ${response.statusText}`);
    28
        }
    29
    
    
    30
        // Parse the JSON response
    31
        const data = await response.json();
    32
    
    
    33
        // Return the parsed data
    34
        return data;
    35
      } catch (error) {
    36
        // Handle any errors that occurred during the fetch
    37
        console.error('Error fetching Notion database:', error);
    38
        throw error; // Rethrow the error to be handled by the caller
    39
      }
    40
    }