0
Get Live Exchange Rates
One script reply has been approved by the moderators Verified

Returns the most recent exchange rates for a given set of currencies.

Created by hugo697 5 days ago Viewed 1 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 5 days ago
1
type Abstractapi = {
2
	apiKey: string
3
}
4

5
export async function main(
6
	resource: Abstractapi,
7
	baseCurrency: string,
8
	targetCurrencies?: string[]
9
) {
10
	const queryParams = new URLSearchParams({
11
		api_key: resource.apiKey,
12
		base: baseCurrency
13
	})
14

15
	// If target currencies are provided, convert them to a comma-separated string
16
	if (targetCurrencies && targetCurrencies.length > 0) {
17
		queryParams.append('target', targetCurrencies.join(','))
18
	}
19

20
	const endpoint = `https://exchange-rates.abstractapi.com/v1/live?${queryParams.toString()}`
21

22
	const response = await fetch(endpoint, {
23
		method: 'GET'
24
	})
25

26
	if (!response.ok) {
27
		throw new Error(`HTTP error! status: ${response.status}`)
28
	}
29

30
	const data = await response.json()
31

32
	return data
33
}
34