0

Search For News Articles

by
Published Dec 20, 2024

Search through millions of articles from over 150,000 large and small news sources and blogs.

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
		q?: string
10
		searchIn?: string
11
		sources?: string
12
		domains?: string
13
		excludeDomains?: string
14
		from?: string // format: YYYY-MM-DD
15
		to?: string // format: YYYY-MM-DD
16
		language?:
17
			| 'ar'
18
			| 'de'
19
			| 'en'
20
			| 'es'
21
			| 'fr'
22
			| 'he'
23
			| 'it'
24
			| 'nl'
25
			| 'no'
26
			| 'pt'
27
			| 'ru'
28
			| 'sv'
29
			| 'ud'
30
			| 'zh'
31
		sortBy?: 'relevancy' | 'popularity' | 'publishedAt'
32
		pageSize?: number // max 100
33
		page?: number
34
	}
35
) {
36
	const url = new URL('https://newsapi.org/v2/everything')
37

38
	// Append the API key for authentication
39
	url.searchParams.append('apiKey', resource.apiKey)
40

41
	// Append the query parameters if provided
42
	for (const [key, value] of Object.entries(params)) {
43
		if (value !== undefined && value !== '') {
44
			url.searchParams.append(key, value.toString())
45
		}
46
	}
47

48
	const response = await fetch(url.toString(), {
49
		method: 'GET',
50
		headers: {
51
			accept: 'application/json'
52
		}
53
	})
54

55
	if (!response.ok) {
56
		const error = await response.text()
57
		throw new Error(`HTTP error! status: ${response.status}`)
58
	}
59

60
	const data = await response.json()
61

62
	return data
63
}
64