0
Fetch data from Notion database
One script reply has been approved by the moderators Verified

This script is designed to fetch data from a specific Notion database using the Notion API. It requires a Notion object containing an API token for authentication. The script sets up the necessary headers, including authorization and the Notion API version, and makes a POST request to the Notion database's URL. It handles both the successful retrieval of data, returning the parsed JSON, and errors by logging them and rethrowing to be handled by the caller.

Created by henri186 250 days ago Viewed 5487 times
0
Submitted by henri186 Bun
Verified 250 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
}