0

List Headline Sources

by
Published Dec 20, 2024

This endpoint returns the subset of news publishers that top headlines are available from.

Script newsapi Verified

The script

Submitted by hugo697 Bun
Verified 536 days ago
1
//native
2
type Newsapi = {
3
	apiKey: string
4
}
5

6
export async function main(
7
	resource: Newsapi,
8
	params?: {
9
		category?:
10
			| 'business'
11
			| 'entertainment'
12
			| 'general'
13
			| 'health'
14
			| 'science'
15
			| 'sports'
16
			| 'technology'
17
		country?:
18
			| 'ae'
19
			| 'ar'
20
			| 'at'
21
			| 'au'
22
			| 'be'
23
			| 'bg'
24
			| 'br'
25
			| 'ca'
26
			| 'ch'
27
			| 'cn'
28
			| 'co'
29
			| 'cu'
30
			| 'cz'
31
			| 'de'
32
			| 'eg'
33
			| 'fr'
34
			| 'gb'
35
			| 'gr'
36
			| 'hk'
37
			| 'hu'
38
			| 'id'
39
			| 'ie'
40
			| 'il'
41
			| 'in'
42
			| 'it'
43
			| 'jp'
44
			| 'kr'
45
			| 'lt'
46
			| 'lv'
47
			| 'ma'
48
			| 'mx'
49
			| 'my'
50
			| 'ng'
51
			| 'nl'
52
			| 'no'
53
			| 'nz'
54
			| 'ph'
55
			| 'pl'
56
			| 'pt'
57
			| 'ro'
58
			| 'rs'
59
			| 'ru'
60
			| 'sa'
61
			| 'se'
62
			| 'sg'
63
			| 'si'
64
			| 'sk'
65
			| 'th'
66
			| 'tr'
67
			| 'tw'
68
			| 'ua'
69
			| 'us'
70
			| 've'
71
			| 'za'
72
		language?:
73
			| 'ar'
74
			| 'de'
75
			| 'en'
76
			| 'es'
77
			| 'fr'
78
			| 'he'
79
			| 'it'
80
			| 'nl'
81
			| 'no'
82
			| 'pt'
83
			| 'ru'
84
			| 'se'
85
			| 'ud'
86
			| 'zh'
87
	}
88
) {
89
	const url = new URL('https://newsapi.org/v2/top-headlines/sources')
90

91
	// Append the API key for authentication
92
	url.searchParams.append('apiKey', resource.apiKey)
93

94
	// Append the query parameters if provided
95
	for (const [key, value] of Object.entries(params || {})) {
96
		if (value !== undefined) {
97
			url.searchParams.append(key, value.toString())
98
		}
99
	}
100

101
	const response = await fetch(url.toString(), {
102
		method: 'GET',
103
		headers: {
104
			accept: 'application/json'
105
		}
106
	})
107

108
	if (!response.ok) {
109
		const error = await response.text()
110
		console.error('Error:', error)
111
		throw new Error(`HTTP error! status: ${response.status}`)
112
	}
113

114
	const data = await response.json()
115

116
	return data
117
}
118