Install Required Packages
- To interact with the Climacell (also known as Tomorrow.io) API in Node.js, you need to install the `axios` package to make HTTP requests.
- Additionally, the `dotenv` package is recommended for managing API keys securely. Run the command below to install both:
npm install axios dotenv
Set Up Environment Variables
- Create a `.env` file in your project’s root directory. This file will store your API key, avoiding hardcoding sensitive information in your codebase.
- Add your Climacell API key in the following format within your `.env` file:
CLIMACELL_API_KEY=your_api_key_here
Configure the Axios Instance
- To simplify HTTP request creation and error handling, configure an `axios` instance that defines default settings for your Climacell API interaction.
- Create a new file named `axiosInstance.js` and use the code below for setup:
require('dotenv').config();
const axios = require('axios');
const axiosInstance = axios.create({
baseURL: 'https://api.tomorrow.io/v4',
headers: {
'Accept': 'application/json',
'apikey': process.env.CLIMACELL_API_KEY
}
});
module.exports = axiosInstance;
Create a Function to Fetch Weather Data
- Create a JavaScript file named `getWeather.js` where you will define a function to fetch the desired weather data from Climacell.
- Use the code snippet below to create a function that retrieves the current weather conditions for a specific location:
const axiosInstance = require('./axiosInstance');
async function getWeather(latitude, longitude) {
try {
const response = await axiosInstance.get('/weather/nowcast', {
params: {
lat: latitude,
lon: longitude,
fields: ['temperature', 'humidity', 'windSpeed'],
}
});
return response.data;
} catch (error) {
console.error('Error fetching weather data:', error);
throw error;
}
}
module.exports = getWeather;
Use the Weather Fetch Function
- In your `index.js` or main application file, utilize the weather-fetch function to access and print the weather forecast details.
- Here is an example of how you can integrate and call the `getWeather` function:
const getWeather = require('./getWeather');
const latitude = 40.7128; // Example coordinates for New York City
const longitude = -74.0060;
getWeather(latitude, longitude)
.then(data => {
console.log('Weather Data:', data);
})
.catch(error => {
console.error('Failed to fetch weather:', error);
});
Optimize for Scalability
- For production applications, consider implementing additional request validation, error handling, and caching mechanisms to optimize performance and reliability.
- Utilizing tools such as Redis for caching can significantly reduce the number of API requests and enhance responsiveness.