0

Get Top Headlines

by
Published Dec 20, 2024

This endpoint provides live top and breaking headlines for a country, specific category in a country, single source, or multiple sources.

Script newsapi Verified

The script

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

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

80
	// Append the API key for authentication
81
	url.searchParams.append('apiKey', resource.apiKey)
82

83
	// Append the query parameters if provided
84
	for (const [key, value] of Object.entries(params)) {
85
		if (value !== undefined && value !== '') {
86
			url.searchParams.append(key, value.toString())
87
		}
88
	}
89

90
	const response = await fetch(url.toString(), {
91
		method: 'GET',
92
		headers: {
93
			accept: 'application/json'
94
		}
95
	})
96

97
	if (!response.ok) {
98
		const error = await response.text()
99
		console.error('Error:', error)
100
		throw new Error(`HTTP error! status: ${response.status}`)
101
	}
102

103
	const data = await response.json()
104

105
	return data
106
}
107