0

Download document file.

by
Published Oct 17, 2025

Downloads the file associated with the provided Document ID.

Script personio Verified

The script

Submitted by hugo697 Bun
Verified 235 days ago
1
//native
2
type Personio = {
3
	clientId: string
4
	clientSecret: string
5
}
6
/**
7
 * Download document file.
8
 * Downloads the file associated with the provided Document ID.
9
 */
10
export async function main(auth: Personio, document_id: string) {
11
	const url = new URL(
12
		`https://api.personio.de/v2/document-management/documents/${document_id}/download`
13
	)
14

15
	const response = await fetch(url, {
16
		method: 'GET',
17
		headers: {
18
			Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token'))
19
		},
20
		body: undefined
21
	})
22
	if (!response.ok) {
23
		const text = await response.text()
24
		throw new Error(`${response.status} ${text}`)
25
	}
26
	return await response.text()
27
}
28

29
async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> {
30
	const params = new URLSearchParams({
31
		grant_type: 'client_credentials',
32
		client_id: auth.clientId,
33
		client_secret: auth.clientSecret
34
	})
35

36
	const response = await fetch(tokenUrl, {
37
		method: 'POST',
38
		headers: {
39
			Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`),
40
			'Content-Type': 'application/x-www-form-urlencoded'
41
		},
42
		body: params.toString()
43
	})
44

45
	if (!response.ok) {
46
		const text = await response.text()
47
		throw new Error(`OAuth token request failed: ${response.status} ${text}`)
48
	}
49

50
	const data = await response.json()
51
	return data.access_token
52
}
53
}
54