0

Create Record

by
Published Sep 27, 2024
Script datocms Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 621 days ago
1
type Datocms = {
2
	apiKey: string
3
}
4

5
export async function main(resource: Datocms, modelId: string, recordData: Record<string, any>) {
6
	const endpoint = `https://site-api.datocms.com/items`
7

8
	const body = {
9
		data: {
10
			type: 'item',
11
			attributes: recordData,
12
			relationships: {
13
				item_type: {
14
					data: {
15
						type: 'item_type',
16
						id: modelId
17
					}
18
				}
19
			}
20
		}
21
	}
22

23
	const response = await fetch(endpoint, {
24
		method: 'POST',
25
		headers: {
26
			Authorization: `Bearer ${resource.apiKey}`,
27
			Accept: 'application/json',
28
			'X-Api-Version': '3',
29
			'Content-Type': 'application/vnd.api+json'
30
		},
31
		body: JSON.stringify(body)
32
	})
33

34
	if (!response.ok) {
35
		throw new Error(`HTTP error! status: ${response.status}`)
36
	}
37

38
	const data = await response.json()
39

40
	return data
41
}
42