0

Weather History

by
Published Dec 20, 2024

History weather API method returns historical weather for a date on or after 1st Jan, 2010

Script weatherapi Verified

The script

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

6
export async function main(
7
	auth: Weatherapi,
8
	params: {
9
		q: string
10
		dt: string
11
		unixdt?: number
12
		end_dt?: string
13
		unixend_dt?: number
14
		hour?: number
15
		lang?:
16
			| 'ar'
17
			| 'bn'
18
			| 'bg'
19
			| 'zh'
20
			| 'zh_tw'
21
			| 'cs'
22
			| 'da'
23
			| 'nl'
24
			| 'fi'
25
			| 'fr'
26
			| 'de'
27
			| 'el'
28
			| 'hi'
29
			| 'hu'
30
			| 'it'
31
			| 'ja'
32
			| 'jv'
33
			| 'ko'
34
			| 'zh_cmn'
35
			| 'mr'
36
			| 'pl'
37
			| 'pt'
38
			| 'pa'
39
			| 'ro'
40
			| 'ru'
41
			| 'sr'
42
			| 'si'
43
			| 'sk'
44
			| 'es'
45
			| 'sv'
46
			| 'ta'
47
			| 'te'
48
			| 'tr'
49
			| 'uk'
50
			| 'ur'
51
			| 'vi'
52
			| 'zh_wuu'
53
			| 'zh_hsn'
54
			| 'zh_yue'
55
			| 'zu'
56
	}
57
) {
58
	const url = new URL(`http://api.weatherapi.com/v1/history.json`)
59

60
	// Append the API key for authentication
61
	url.searchParams.append('key', auth.apiKey)
62

63
	// Append the query parameters if provided
64
	for (const [key, value] of Object.entries(params)) {
65
		if (value !== undefined && value !== '') {
66
			url.searchParams.append(key, value.toString())
67
		}
68
	}
69

70
	const response = await fetch(url.toString(), {
71
		method: 'GET'
72
	})
73

74
	if (!response.ok) {
75
		const errorText = await response.text()
76
		throw new Error(
77
			`WeatherAPI request failed: ${response.status} ${response.statusText} - ${errorText}`
78
		)
79
	}
80

81
	return await response.json()
82
}
83