0

Create Field

by
Published Sep 27, 2024
Script datocms Verified

The script

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

5
export async function main(
6
	resource: Datocms,
7
	modelId: string,
8
	fieldData: {
9
		label: string
10
		field_type: string
11
		api_key: string
12
		localized?: boolean
13
		hint?: string
14
		validators?: Record<string, any>
15
		appearance?: Record<string, any>
16
		default_value?: any
17
		required?: boolean
18
	}
19
) {
20
	const endpoint = `https://site-api.datocms.com/item-types/${modelId}/fields`
21

22
	// Construct the request body
23
	const body = {
24
		data: {
25
			type: 'field',
26
			attributes: fieldData
27
		}
28
	}
29

30
	const response = await fetch(endpoint, {
31
		method: 'POST',
32
		headers: {
33
			Authorization: `Bearer ${resource.apiKey}`,
34
			Accept: 'application/json',
35
			'X-Api-Version': '3',
36
			'Content-Type': 'application/vnd.api+json'
37
		},
38
		body: JSON.stringify(body)
39
	})
40

41
	if (!response.ok) {
42
		throw new Error(`HTTP error! status: ${response.status}`)
43
	}
44

45
	const data = await response.json()
46

47
	return data
48
}
49