Share
Explore

Node.js Weather API Lab

Learning Outcomes:
This exercise will teach students how to
interact with third-party APIs,
handle JSON data, and
integrate real-time data into their applications.
It also exposes us to working with external services and managing API keys, which are common tasks in full-stack development.
Here's a detailed lab exercise plan for connecting to the OpenWeatherMap API:

Free weather APIs that you can use. One reliable alternative is the National Weather Service (NWS) API provided by the US Weather Bureau. Here are a few options:

1. National Weather Service (NWS) API

The National Weather Service provides a comprehensive and free API for accessing weather data in the United States.
Key Features:
Free access to a wide range of weather data including forecasts, current conditions, alerts, and more.
Comprehensive documentation.
No API key required.
API Endpoint Example:
Forecast: https://api.weather.gov/gridpoints/{office}/{grid X},{grid Y}/forecast
Alerts: https://api.weather.gov/alerts/active
How to Use:
Visit the to get started.
Example request for weather forecast:
bash
Copy code
curl -X GET "https://api.weather.gov/gridpoints/MPX/116,72/forecast"

2. WeatherAPI

WeatherAPI offers a free tier that includes current weather, forecast, and historical weather data.
Key Features:
Free tier with generous usage limits.
Simple and easy-to-use endpoints.
Global coverage.
API Endpoint Example:
Current Weather: http://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London
How to Use:
Sign up at to get a free API key.
Example request for current weather:
bash
Copy code
curl -X GET "http://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London"

3. Open-Meteo

Open-Meteo provides free access to weather data with a focus on forecast data. No API key is required for basic usage.
Key Features:
Free access without the need for an API key.
Focus on forecast data.
Easy-to-use endpoints.
API Endpoint Example:
Forecast: https://api.open-meteo.com/v1/forecast?latitude=35.6895&longitude=139.6917&hourly=temperature_2m
How to Use:
Example request for a weather forecast:
bash
Copy code
curl -X GET "https://api.open-meteo.com/v1/forecast?latitude=35.6895&longitude=139.6917&hourly=temperature_2m"

Example: Using the NWS API in Node.js

Here's an example of how you can use the NWS API in a Node.js application:

1. Setup the Project

bash
Copy code
mkdir nws-weather-app
cd nws-weather-app
npm init -y
npm install express node-fetch

2. Create the Server

server.js:
javascript
Copy code
import express from 'express';
import fetch from 'node-fetch';

const app = express();
const port = 3000;

app.use(express.static('public'));

app.get('/weather', async (req, res) => {
const { latitude, longitude } = req.query;

if (!latitude || !longitude) {
return res.status(400).json({ error: 'Latitude and longitude are required' });
}

const forecastUrl = `https://api.weather.gov/points/${latitude},${longitude}`;

try {
const pointResponse = await fetch(forecastUrl);
const pointData = await pointResponse.json();
const forecastEndpoint = pointData.properties.forecast;

const forecastResponse = await fetch(forecastEndpoint);
const forecastData = await forecastResponse.json();

res.json(forecastData);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch weather data' });
}
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});

3. Create a Simple Frontend

public/index.html:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
</head>
<body>
<h1>Weather App</h1>
<form id="weatherForm">
<input type="text" id="latitude" placeholder="Latitude" required>
<input type="text" id="longitude" placeholder="Longitude" required>
<button type="submit">Get Weather</button>
</form>
<h2>Forecast</h2>
<div id="forecast"></div>

<script>
document.getElementById('weatherForm').addEventListener('submit', function(event) {
event.preventDefault();

const latitude = document.getElementById('latitude').value;
const longitude = document.getElementById('longitude').value;

fetch(`/weather?latitude=${latitude}&longitude=${longitude}`)
.then(response => response.json())
.then(data => {
const forecastDiv = document.getElementById('forecast');
forecastDiv.innerHTML = '';

if (data.properties && data.properties.periods) {
data.properties.periods.forEach(period => {
const periodDiv = document.createElement('div');
periodDiv.innerHTML = `<p>${period.name}: ${period.detailedForecast}</p>`;
forecastDiv.appendChild(periodDiv);
});
} else {
forecastDiv.innerHTML = '<p>No forecast available</p>';
}
})
.catch(error => {
console.error('Error fetching weather data:', error);
document.getElementById('forecast').innerHTML = '<p>Error fetching weather data</p>';
});
});
</script>
</body>
</html>

4. Run the Server

bash
Copy code
node server.js

Open your browser and navigate to http://localhost:3000. Enter the latitude and longitude of your location to get the weather forecast.

Conclusion

These alternative weather APIs provide reliable and free access to weather data, allowing you to integrate weather information into your applications. Choose the one that best fits your needs and follow the documentation to get started.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.