0

Weather Forecast

by
Published Dec 20, 2024

Forecast weather API method returns, depending upon your price plan level, upto next 14 day weather forecast and weather alert

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
		days: number
11
		dt?: string
12
		unixdt?: number
13
		hour?: number
14
		alerts?: 'yes' | 'no'
15
		aqi?: 'yes' | 'no'
16
		tp?: string
17
		lang?:
18
			| 'ar'
19
			| 'bn'
20
			| 'bg'
21
			| 'zh'
22
			| 'zh_tw'
23
			| 'cs'
24
			| 'da'
25
			| 'nl'
26
			| 'fi'
27
			| 'fr'
28
			| 'de'
29
			| 'el'
30
			| 'hi'
31
			| 'hu'
32
			| 'it'
33
			| 'ja'
34
			| 'jv'
35
			| 'ko'
36
			| 'zh_cmn'
37
			| 'mr'
38
			| 'pl'
39
			| 'pt'
40
			| 'pa'
41
			| 'ro'
42
			| 'ru'
43
			| 'sr'
44
			| 'si'
45
			| 'sk'
46
			| 'es'
47
			| 'sv'
48
			| 'ta'
49
			| 'te'
50
			| 'tr'
51
			| 'uk'
52
			| 'ur'
53
			| 'vi'
54
			| 'zh_wuu'
55
			| 'zh_hsn'
56
			| 'zh_yue'
57
			| 'zu'
58
	}
59
) {
60
	const url = new URL(`http://api.weatherapi.com/v1/forecast.json`)
61

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

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

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

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

83
	return await response.json()
84
}
85