0

Location Search

by
Published Dec 20, 2024

Search or Autocomplete API returns matching cities and towns as an array of Location object

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
	}
11
) {
12
	const url = new URL(`http://api.weatherapi.com/v1/search.json`)
13

14
	// Append the API key for authentication
15
	url.searchParams.append('key', auth.apiKey)
16

17
	// Append the query parameters if provided
18
	for (const [key, value] of Object.entries(params)) {
19
		if (value !== undefined && value !== '') {
20
			url.searchParams.append(key, value.toString())
21
		}
22
	}
23

24
	const response = await fetch(url.toString(), {
25
		method: 'GET'
26
	})
27

28
	if (!response.ok) {
29
		const errorText = await response.text()
30
		throw new Error(
31
			`WeatherAPI request failed: ${response.status} ${response.statusText} - ${errorText}`
32
		)
33
	}
34

35
	return await response.json()
36
}
37