0

Insert record with ID

by
Published Apr 8, 2025

By default, IDs are auto-generated when data is inserted into Xata. Sending a request to this endpoint allows us to insert a record with a pre-existing ID, bypassing the default automatic ID generation.

Script xata Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Xata = {
3
	apiKey: string
4
	workspaceUrl: string
5
}
6
/**
7
 * Insert record with ID
8
 * By default, IDs are auto-generated when data is inserted into Xata. Sending a request to this endpoint allows us to insert a record with a pre-existing ID, bypassing the default automatic ID generation.
9
 */
10
export async function main(
11
	auth: Xata,
12
	db_branch_name: string,
13
	table_name: string,
14
	record_id: string,
15
	columns: string | undefined,
16
	createOnly: string | undefined,
17
	ifVersion: string | undefined,
18
	body: {}
19
) {
20
	const url = new URL(
21
		`${auth.workspaceUrl}/db/${db_branch_name}/tables/${table_name}/data/${record_id}`
22
	)
23
	for (const [k, v] of [
24
		['columns', columns],
25
		['createOnly', createOnly],
26
		['ifVersion', ifVersion]
27
	]) {
28
		if (v !== undefined && v !== '' && k !== undefined) {
29
			url.searchParams.append(k, v)
30
		}
31
	}
32
	const response = await fetch(url, {
33
		method: 'PUT',
34
		headers: {
35
			'Content-Type': 'application/json',
36
			Authorization: 'Bearer ' + auth.apiKey
37
		},
38
		body: JSON.stringify(body)
39
	})
40
	if (!response.ok) {
41
		const text = await response.text()
42
		throw new Error(`${response.status} ${text}`)
43
	}
44
	return await response.json()
45
}
46