Update page properties

This script updates a specific page in Notion using the Notion API. It requires the Notion API token, the ID of the page to be updated, and the new property values for the update. The script sets up the necessary headers, constructs the request body with the provided property updates, and sends a PATCH request to the Notion API to apply the updates. If successful, it returns the updated page data; otherwise, it throws an error with details about the failure.

Script notion Verified

by henri186 ยท 4/16/2024

The script

Submitted by henri186 Bun
Verified 372 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, pageId: string, propertyUpdates: any): Promise<any> {
7
  // URL to update a specific page
8
  const pageUrl = `https://api.notion.com/v1/pages/${pageId}`;
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
  // Set up the body with property updates
18
  const body = {
19
    properties: propertyUpdates
20
  };
21

22
  // Perform the fetch request to update the Notion page
23
  try {
24
    const response = await fetch(pageUrl, {
25
      method: 'PATCH', // The Notion API requires a PATCH request to update a page
26
      headers: headers,
27
      body: JSON.stringify(body)
28
    });
29

30
    // Check if the request was successful
31
    if (!response.ok) {
32
      throw new Error(`Failed to update Notion page: ${response.status} ${response.statusText}`);
33
    }
34

35
    // Parse the JSON response
36
    const data = await response.json();
37

38
    // Return the updated data
39
    return data;
40
  } catch (error) {
41
    console.error('Error updating Notion page:', error);
42
    throw error; // Rethrow the error to be handled by the caller
43
  }
44
}