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

Returns the exchange rates for a specific date for a given set of currencies.

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

5
export async function main(
6
	resource: Abstractapi,
7
	baseCurrency: string,
8
	date: `${number}-${number}-${number}`, // YYYY-MM-DD
9
	targetCurrencies?: string[]
10
) {
11
	const queryParams = new URLSearchParams({
12
		api_key: resource.apiKey,
13
		base: baseCurrency,
14
		date: date
15
	})
16

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

22
	const endpoint = `https://exchange-rates.abstractapi.com/v1/historical?${queryParams.toString()}`
23

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

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

32
	const data = await response.json()
33

34
	return data
35
}
36