Create a codespace for the authenticated user

Creates a new codespace, owned by the authenticated user. This endpoint requires either a `repository_id` OR a `pull_request` but not both. You must authenticate using an access token with the `codespace` scope to use this endpoint. GitHub Apps must have write access to the `codespaces` repository permission to use this endpoint.

Script github Verified

by hugo697 ยท 10/25/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 367 days ago
1
type Github = {
2
  token: string;
3
};
4
/**
5
 * Create a codespace for the authenticated user
6
 * Creates a new codespace, owned by the authenticated user.
7

8
This endpoint requires either a `repository_id` OR a `pull_request` but not both.
9

10
You must authenticate using an access token with the `codespace` scope to use this endpoint.
11

12
GitHub Apps must have write access to the `codespaces` repository permission to use this endpoint.
13
 */
14
export async function main(
15
  auth: Github,
16
  body:
17
    | {
18
        client_ip?: string;
19
        devcontainer_path?: string;
20
        display_name?: string;
21
        idle_timeout_minutes?: number;
22
        location?: string;
23
        machine?: string;
24
        multi_repo_permissions_opt_out?: boolean;
25
        ref?: string;
26
        repository_id: number;
27
        retention_period_minutes?: number;
28
        working_directory?: string;
29
        [k: string]: unknown;
30
      }
31
    | {
32
        devcontainer_path?: string;
33
        idle_timeout_minutes?: number;
34
        location?: string;
35
        machine?: string;
36
        pull_request: {
37
          pull_request_number: number;
38
          repository_id: number;
39
          [k: string]: unknown;
40
        };
41
        working_directory?: string;
42
        [k: string]: unknown;
43
      }
44
) {
45
  const url = new URL(`https://api.github.com/user/codespaces`);
46

47
  const response = await fetch(url, {
48
    method: "POST",
49
    headers: {
50
      "Content-Type": "application/json",
51
      Authorization: "Bearer " + auth.token,
52
    },
53
    body: JSON.stringify(body),
54
  });
55
  if (!response.ok) {
56
    const text = await response.text();
57
    throw new Error(`${response.status} ${text}`);
58
  }
59
  return await response.json();
60
}
61