0

Create List

by
Published today

Create a list in a site. `template` is a SharePoint list template such as `genericList`, `documentLibrary`, `events` or `tasks`. `columns` takes Graph column definitions, e.g. `[{ "name": "Author", "text": {} }, { "name": "PageCount", "number": {} }]`; a Title column always exists. Requires Sites.Manage.All, not a connection default: tick it when connecting.

Script ms_sharepoint Verified

The script

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

3
const graph = "https://graph.microsoft.com/v1.0"
4

5
export type DynSelect_site_id = string
6

7
export async function site_id(auth: RT.MsSharepoint) {
8
  const response = await fetch(
9
    `${graph}/sites?search=*&$select=id,displayName,webUrl&$top=200`,
10
    {
11
      headers: {
12
        Authorization: `Bearer ${auth.token}`,
13
        Accept: "application/json",
14
      },
15
    }
16
  )
17
  if (!response.ok) {
18
    throw new Error(`${response.status} ${await response.text()}`)
19
  }
20
  const { value } = (await response.json()) as {
21
    value: { id: string; displayName: string; webUrl: string }[]
22
  }
23
  return value.map((s) => ({
24
    value: s.id,
25
    label: `${s.displayName} (${s.webUrl})`,
26
  }))
27
}
28

29
/**
30
 * Create List
31
 * Create a list in a site. `template` is a SharePoint list template such as `genericList`, `documentLibrary`, `events` or `tasks`. `columns` takes Graph column definitions, e.g. `[{ "name": "Author", "text": {} }, { "name": "PageCount", "number": {} }]`; a Title column always exists. Requires Sites.Manage.All, not a connection default: tick it when connecting.
32
 */
33
export async function main(
34
  auth: RT.MsSharepoint,
35
  site_id: DynSelect_site_id,
36
  display_name: string,
37
  description: string | undefined,
38
  template: string = "genericList",
39
  columns: { [key: string]: any }[] | undefined
40
) {
41
  const body: { [key: string]: any } = {
42
    displayName: display_name,
43
    list: { template },
44
  }
45
  if (description != null && description !== "") body.description = description
46
  if (columns?.length) body.columns = columns
47

48
  const response = await fetch(`${graph}/sites/${site_id}/lists`, {
49
    method: "POST",
50
    headers: {
51
      Authorization: `Bearer ${auth.token}`,
52
      "Content-Type": "application/json",
53
      Accept: "application/json",
54
    },
55
    body: JSON.stringify(body),
56
  })
57

58
  if (!response.ok) {
59
    throw new Error(`${response.status} ${await response.text()}`)
60
  }
61

62
  return await response.json()
63
}
64