0

Update Data Source

by
Published today

Rename a data source, or add, rename, retype or remove its columns.

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
 * Update Data Source
32
 * Rename a data source or change its columns. `properties` maps a column name to its new schema, or a type name for simple columns: a new name adds a column, an existing one is retyped, {"name": "New name"} renames it, and null removes it. Columns left out are unchanged.
33
 */
34
export async function main(
35
  auth: RT.Notion,
36
  data_source_id: DynSelect_data_source_id,
37
  title: string | undefined,
38
  properties: { [key: string]: any } | undefined
39
) {
40
  const body: { [key: string]: any } = {}
41
  if (title !== undefined && title !== "") {
42
    body.title = [{ text: { content: title } }]
43
  }
44
  if (properties && Object.keys(properties).length) {
45
    body.properties = {}
46
    for (const [name, value] of Object.entries(properties)) {
47
      body.properties[name] =
48
        typeof value === "string" ? { [value]: {} } : value
49
    }
50
  }
51

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

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

70
  return await response.json()
71
}
72