0

Import Workspace Object

by
Published 4 days ago

Import a notebook or file into the workspace. Pass content as plain text — it is base64-encoded for you. For SOURCE format set the language (PYTHON, SQL, SCALA, R).

Script databricks Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 5 days ago
1
//native
2

3
/**
4
 * Import Workspace Object
5
 * Import a notebook or file into the workspace. Pass content as plain text — it is base64-encoded for you. For SOURCE format set the language (PYTHON, SQL, SCALA, R).
6
 */
7
export async function main(
8
  auth: RT.Databricks,
9
  path: string,
10
  content: string,
11
  format: "SOURCE" | "HTML" | "JUPYTER" | "DBC" | "AUTO" = "SOURCE",
12
  language: "PYTHON" | "SQL" | "SCALA" | "R" | undefined,
13
  overwrite: boolean = false
14
) {
15
  const base = auth.workspace_url.replace(/\/$/, "")
16
  const url = new URL(`${base}/api/2.0/workspace/import`)
17

18
  // base64-encode the UTF-8 content without overflowing the call stack on large inputs
19
  const bytes = new TextEncoder().encode(content)
20
  let binary = ""
21
  for (const b of bytes) binary += String.fromCharCode(b)
22
  const encoded = btoa(binary)
23

24
  const body: { [key: string]: any } = {
25
    path,
26
    content: encoded,
27
    format,
28
    overwrite,
29
  }
30
  if (language !== undefined) body.language = language
31

32
  const response = await fetch(url, {
33
    method: "POST",
34
    headers: {
35
      Authorization: `Bearer ${auth.token}`,
36
      "Content-Type": "application/json",
37
      Accept: "application/json",
38
    },
39
    body: JSON.stringify(body),
40
  })
41

42
  if (!response.ok) {
43
    throw new Error(`${response.status} ${await response.text()}`)
44
  }
45

46
  const text = await response.text()
47
  return text ? JSON.parse(text) : { success: true }
48
}
49