### Install Open-Meteo SDK Source: https://github.com/open-meteo/typescript/blob/main/README.md Command to install the openmeteo package via npm. ```bash npm install openmeteo ``` -------------------------------- ### Fetch and Process Weather Data Source: https://github.com/open-meteo/typescript/blob/main/README.md Demonstrates how to use fetchWeatherApi to retrieve weather data and parse the FlatBuffer response into a structured format for current, hourly, and daily metrics. ```typescript import { fetchWeatherApi } from 'openmeteo'; const params = { latitude: [52.54], longitude: [13.41], current: 'temperature_2m,weather_code,wind_speed_10m,wind_direction_10m', hourly: 'temperature_2m,precipitation', daily: 'weather_code,temperature_2m_max,temperature_2m_min' }; const url = 'https://api.open-meteo.com/v1/forecast'; const responses = await fetchWeatherApi(url, params); const range = (start: number, stop: number, step: number) => Array.from({ length: (stop - start) / step }, (_, i) => start + i * step); const response = responses[0]; const utcOffsetSeconds = response.utcOffsetSeconds(); const current = response.current()!; const hourly = response.hourly()!; const daily = response.daily()!; const weatherData = { current: { time: new Date((Number(current.time()) + utcOffsetSeconds) * 1000), temperature: current.variables(0)!.value(), weatherCode: current.variables(1)!.value(), windSpeed: current.variables(2)!.value(), windDirection: current.variables(3)!.value() }, hourly: { time: range(Number(hourly.time()), Number(hourly.timeEnd()), hourly.interval()).map( (t) => new Date((t + utcOffsetSeconds) * 1000) ), temperature: hourly.variables(0)!.valuesArray()!, precipitation: hourly.variables(1)!.valuesArray()!, }, daily: { time: range(Number(daily.time()), Number(daily.timeEnd()), daily.interval()).map( (t) => new Date((t + utcOffsetSeconds) * 1000) ), weatherCode: daily.variables(0)!.valuesArray()!, temperatureMax: daily.variables(1)!.valuesArray()!, temperatureMin: daily.variables(2)!.valuesArray()!, } }; ``` -------------------------------- ### Authenticate API Requests with Headers in TypeScript Source: https://github.com/open-meteo/typescript/blob/main/README.md Demonstrates how to pass authentication headers to the `fetchWeatherApi` function for secured API endpoints. This is useful when the API requires tokens or API keys for access. The `fetchOptions` parameter accepts a `headers` object for this purpose. ```typescript import { fetchWeatherApi } from 'openmeteo'; const params = { latitude: [52.54], longitude: [13.41], current: 'temperature_2m,weather_code,wind_speed_10m,wind_direction_10m', hourly: 'temperature_2m,precipitation', daily: 'weather_code,temperature_2m_max,temperature_2m_min' }; const url = 'https://api.self-host.example.net/v1/forecast'; const fetchOptions = { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } }; const responses = await fetchWeatherApi(url, params, 3, 0.2, 2, fetchOptions); // Process the response as shown in the previous example ``` -------------------------------- ### Cancel API Requests with AbortController in TypeScript Source: https://github.com/open-meteo/typescript/blob/main/README.md Shows how to use the `AbortController` to cancel an ongoing API request. This is crucial for improving user experience by preventing unnecessary network activity when a request is no longer needed. The `fetchOptions` parameter accepts a `signal` from an `AbortController`. ```typescript import { fetchWeatherApi } from 'openmeteo'; const params = { latitude: [52.54], longitude: [13.41], current: 'temperature_2m,weather_code,wind_speed_10m,wind_direction_10m', hourly: 'temperature_2m,precipitation', daily: 'weather_code,temperature_2m_max,temperature_2m_min' }; const url = 'https://api.open-meteo.com/v1/forecast'; const controller = new AbortController(); const fetchOptions = { signal: controller.signal }; // Start the request const fetchPromise = fetchWeatherApi(url, params, 3, 0.2, 2, fetchOptions); // Abort the request after 5 seconds setTimeout(() => controller.abort(), 5000); try { const responses = await fetchPromise; // Process the response as shown in the previous example } catch (error) { if (error.name === 'AbortError') { console.log('Request was aborted'); } else { console.error('Fetch error:', error); } } ``` -------------------------------- ### Fetch Weather Data with Open-Meteo API Source: https://context7.com/open-meteo/typescript/llms.txt Fetches weather data for a specified location using the Open-Meteo API. It handles FlatBuffer decoding and provides access to current, hourly, and daily forecast data. Requires the 'openmeteo' library and a valid API endpoint. ```typescript import { fetchWeatherApi } from 'openmeteo'; // Define weather parameters const params = { latitude: [52.54], longitude: [13.41], current: 'temperature_2m,weather_code,wind_speed_10m,wind_direction_10m', hourly: 'temperature_2m,precipitation', daily: 'weather_code,temperature_2m_max,temperature_2m_min' }; const url = 'https://api.open-meteo.com/v1/forecast'; const responses = await fetchWeatherApi(url, params); // Helper function to form time ranges const range = (start: number, stop: number, step: number) => Array.from({ length: (stop - start) / step }, (_, i) => start + i * step); // Process response for first location const response = responses[0]; // Access location and timezone attributes const utcOffsetSeconds = response.utcOffsetSeconds(); const timezone = response.timezone(); const timezoneAbbreviation = response.timezoneAbbreviation(); const latitude = response.latitude(); const longitude = response.longitude(); // Extract current weather data const current = response.current()!; const currentWeather = { time: new Date((Number(current.time()) + utcOffsetSeconds) * 1000), temperature: current.variables(0)!.value(), weatherCode: current.variables(1)!.value(), windSpeed: current.variables(2)!.value(), windDirection: current.variables(3)!.value() }; // Extract hourly forecast data const hourly = response.hourly()!; const hourlyData = { time: range(Number(hourly.time()), Number(hourly.timeEnd()), hourly.interval()).map( (t) => new Date((t + utcOffsetSeconds) * 1000) ), temperature: hourly.variables(0)!.valuesArray()!, precipitation: hourly.variables(1)!.valuesArray()! }; // Extract daily forecast data const daily = response.daily()!; const dailyData = { time: range(Number(daily.time()), Number(daily.timeEnd()), daily.interval()).map( (t) => new Date((t + utcOffsetSeconds) * 1000) ), weatherCode: daily.variables(0)!.valuesArray()!, temperatureMax: daily.variables(1)!.valuesArray()!, temperatureMin: daily.variables(2)!.valuesArray()! }; // Output daily forecast for (let i = 0; i < dailyData.time.length; i++) { console.log( dailyData.time[i].toISOString(), dailyData.weatherCode[i], dailyData.temperatureMax[i], dailyData.temperatureMin[i] ); } ``` -------------------------------- ### fetchWeatherApi Function Signature Source: https://github.com/open-meteo/typescript/blob/main/README.md The primary function signature for fetching weather data, including parameters for URL, API configuration, and retry logic. ```typescript async function fetchWeatherApi( url: string, params: any, retries = 3, backoffFactor = 0.2, backoffMax = 2 ): Promise { } ``` -------------------------------- ### Cancel Open-Meteo API Requests with AbortController Source: https://context7.com/open-meteo/typescript/llms.txt Implement request cancellation for Open-Meteo API calls using the standard AbortController. This is useful for scenarios like user-initiated cancellations or enforcing request timeouts, preventing unnecessary resource consumption. ```typescript import { fetchWeatherApi } from 'openmeteo'; const params = { latitude: [52.54], longitude: [13.41], current: 'temperature_2m,weather_code,wind_speed_10m,wind_direction_10m', hourly: 'temperature_2m,precipitation', daily: 'weather_code,temperature_2m_max,temperature_2m_min' }; const url = 'https://api.open-meteo.com/v1/forecast'; const controller = new AbortController(); const fetchOptions = { signal: controller.signal }; // Start the request const fetchPromise = fetchWeatherApi(url, params, 3, 0.2, 2, fetchOptions); // Abort the request after 5 seconds setTimeout(() => controller.abort(), 5000); try { const responses = await fetchPromise; const response = responses[0]; console.log(`Latitude: ${response.latitude()}`); } catch (error) { if (error.name === 'AbortError') { console.log('Request was aborted'); } else { console.error('Fetch error:', error); } } ``` -------------------------------- ### Fetch Weather Data for Multiple Locations Source: https://context7.com/open-meteo/typescript/llms.txt Requests weather data for multiple geographic coordinates in a single API call using the Open-Meteo API. The response array contains a `WeatherApiResponse` object for each location, preserving the order of the input coordinates. Requires the 'openmeteo' library. ```typescript import { fetchWeatherApi } from 'openmeteo'; const params = { latitude: [52.54, 48.1, 48.4], longitude: [13.41, 9.31, 8.5], hourly: ['temperature_2m', 'precipitation'], start_date: '2023-08-01', end_date: '2023-08-03' }; const url = 'https://api.open-meteo.com/v1/forecast'; const responses = await fetchWeatherApi(url, params); // Process each location for (let i = 0; i < responses.length; i++) { const response = responses[i]; console.log(`Location ${i + 1}: Lat ${response.latitude()}, Lon ${response.longitude()}`); const hourly = response.hourly()!; const temperatures = hourly.variables(0)!.valuesArray()!; console.log(`First temperature reading: ${temperatures[0]}°C`); } ``` -------------------------------- ### Configure Custom Retry Behavior with Open-Meteo API Source: https://context7.com/open-meteo/typescript/llms.txt Customize the retry mechanism for the Open-Meteo API by setting specific values for the number of retries, backoff factor, and maximum backoff time. This allows for more granular control over handling transient server errors. ```typescript import { fetchWeatherApi } from 'openmeteo'; const params = { latitude: [52.54], longitude: [13.41], hourly: 'temperature_2m' }; const url = 'https://api.open-meteo.com/v1/forecast'; // Custom retry configuration: // - 5 retries (default: 3) // - 0.5 backoff factor (default: 0.2) // - 5 second max backoff (default: 2) const responses = await fetchWeatherApi(url, params, 5, 0.5, 5); const response = responses[0]; console.log(`Temperature data retrieved for: ${response.latitude()}, ${response.longitude()}`); ``` -------------------------------- ### Authenticate API Requests with Headers using Open-Meteo Source: https://context7.com/open-meteo/typescript/llms.txt Pass custom headers, such as authentication tokens, when making requests to self-hosted or authenticated Open-Meteo API instances. This is essential for securing access to your API endpoints. ```typescript import { fetchWeatherApi } from 'openmeteo'; const params = { latitude: [52.54], longitude: [13.41], current: 'temperature_2m,weather_code,wind_speed_10m,wind_direction_10m', hourly: 'temperature_2m,precipitation', daily: 'weather_code,temperature_2m_max,temperature_2m_min' }; const url = 'https://api.self-host.example.net/v1/forecast'; const fetchOptions = { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } }; // Pass fetchOptions as the 6th parameter const responses = await fetchWeatherApi(url, params, 3, 0.2, 2, fetchOptions); const response = responses[0]; const current = response.current()!; console.log(`Current temperature: ${current.variables(0)!.value()}°C`); ``` -------------------------------- ### Handle API Errors Gracefully with Open-Meteo SDK Source: https://context7.com/open-meteo/typescript/llms.txt Manage various API error types, including client-side errors (400, 429) and server-side errors (500, 502, 504), when interacting with the Open-Meteo API. The SDK automatically retries server errors and throws client errors with descriptive messages. ```typescript import { fetchWeatherApi } from 'openmeteo'; const params = { latitude: [52.54], longitude: [13.41], hourly: 'temperature_2m' }; const url = 'https://api.open-meteo.com/v1/forecast'; try { const responses = await fetchWeatherApi(url, params); const response = responses[0]; const hourly = response.hourly()!; console.log('Weather data retrieved successfully'); } catch (error) { // Error reasons from API are automatically extracted // - 400 Bad Request: Returns error reason from JSON response // - 429 Rate Limited: Returns error reason from JSON response // - 500/502/504: Retries exhausted, throws with statusText console.error('Failed to fetch weather data:', error.message); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.