Building a weather app is a great project for coding beginners to learn the fundamentals of API integration, web development, and testing. In this guide, we'll walk you through the process of creating a simple weather app in Visual Studio Code (VSCode) and how to test the app to ensure your API requests work smoothly. This tutorial covers every step in detail, making it beginner-friendly. Let's start the journey!
Prerequisites
Before starting, make sure you have the following installed:
Visual Studio Code (VSCode): A code editor that supports multiple languages.
Node.js and npm: This will allow you to use JavaScript and install necessary libraries.
EchoAPI for VS Code : A tool for testing APIs and debugging.
Step 1: Set Up the Project in VSCode
1.1 Create a New Directory
Let’s create a folder where we’ll build our weather app.
- Open VSCode.
- Open the Terminal (Ctrl + \ or go to Terminal > New Terminal).
- Run the following commands to create and navigate into a new folder:
mkdir weather-app
cd weather-app
1.2 Initialize a Node.js Project
Now we need to set up Node.js, which will manage our project and its dependencies.
In the terminal, run:
npm init -y
This will create a package.json file, which keeps track of the libraries and settings for our project.
1.3 Install Required Packages
We’ll need a few tools to make our app work. Run this command to install them:
npm install express axios dotenv
Here’s what each package does:
express: Helps create a simple web server.
axios: Allows us to make requests to external APIs (like the weather service).
dotenv: Helps store and manage your API keys securely.
Step 2: Get a Weather API Key
To get real-time weather data, you’ll need an API key from a weather service.
2.1 Sign Up for a Weather API
Head over to OpenWeatherMap (https://openweathermap.org/) and sign up for a free account.
After registering, you’ll get an API key, which is like a password that lets your app fetch weather data.
2.2 Store Your API Key Securely
To keep your API key secure, we’ll store it in a .env file (this is where you can store secret keys safely).
In the terminal, create the .env file by running:
touch .env
Inside the .env file, add your API key like this:
WEATHER_API_KEY = your_api_key_here
Replace your_api_key_here with the actual key you got from OpenWeatherMap.
Step 3: Build the Weather App
Now, let's build the app itself!
3.1 Create the App’s Entry Point
In the terminal, create a new file called app.js. This will be the main file where we write our code.
touch app.js
3.2 Write the Server Code
Open app.js in VSCode and paste the following code:
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const app = express();
const PORT = 3000;
app.get('/weather', async (req, res) => {
const city = req.query.city || 'London'; // Default city is London if no city is provided
const apiKey = process.env.WEATHER_API_KEY;
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
try {
const response = await axios.get(url);
const data = response.data;
res.json({
temperature: data.main.temp,
weather: data.weather[0].description,
city: data.name
});
} catch (error) {
res.status(500).json({ error: 'Failed to fetch weather data' });
}
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
3.3 Breakdown of the Code:
dotenv:
- The line require('dotenv').config(); loads environment variables from a .env file into process.env.
- In this case, we are using it to store the API key (WEATHER_API_KEY) securely.
- This helps you keep sensitive information, like API keys, out of your main code, making your project more secure, especially if you share the code publicly.
/weather route:
- This defines an Express GET route that listens for requests at the /weather endpoint.
- It accepts a city parameter from the query string (req.query.city). For example, if you access the route as /weather?city=New%20York, it will fetch weather data for New York.
- If no city is provided in the request, it defaults to London (const city = req.query.city || 'London').
- The API URL is constructed using the city name and the API key loaded from .env.
axios:
- Axios is used to make HTTP requests. In this case, it's sending a GET request to the OpenWeatherMap API to retrieve the weather data.
- The URL used in the request is https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric, where ${city} is the city requested by the user, and ${apiKey} is the API key from the .env file.
- The response from OpenWeatherMap contains detailed weather information. We are extracting specific data like temperature (data.main.temp), weather description (data.weather[0].description), and city name (data.name).
Error Handling:
- The code is wrapped in a try...catch block to handle potential errors, such as issues with the API request or network failures.
- If an error occurs, the app responds with a 500 status code and an error message Failed to fetch weather data, which is helpful for debugging and for users to know something went wrong.
Express Server:
- The server is set up to listen on port 3000 (const PORT = 3000;).
- Once the server starts, it logs a message to the console: Server running on http://localhost:${PORT}.
- This lets you know the server is up and running and can handle requests at http://localhost:3000/weather.
3.4 Test Your App Locally
To see your app in action, run the following command in the terminal:
node app.js
Now, open your web browser and go to this URL:
http://localhost:3000/weather?city=New%20York
You should see the weather data for New York. If no city is provided, it will show data for London by default.
Step 4: Testing the API Using EchoAPI
4.1 What is EchoAPI?
EchoAPI is a great tool that lets you test your API without having to run your whole app or open a browser. You can simulate requests and check how your app responds—all from within VSCode! And it is FREE!!
4.2 Install EchoAPI in VSCode
You can use EchoAPI in many ways:
Install the EchoAPI-Interceptor for one-click API capture, one-click debugging
Install the EchoAPI for VS Code for a ultra-lightweight API debugging tool for VS Code
Install the EchoAPI for IntelliJ IDEA for one-click API documentation, one-click debugging.
Once EchoAPI for VS Code installed, you can easily test your weather API in VSCode.
4.3 Testing Your Weather App with EchoAPI
Let’s test our app to see how it works:
Open EchoAPI in VSCode.
Create a GET Request and enter the following URL:
http://localhost:3000/weather?city=New%20York
*Send the Request: *
EchoAPI will show you the response from your weather app, which should look something like this:
You can also test what happens when you enter an invalid city name, like:
http://localhost:3000/weather?city=UnknownCity
This should return an error message:
4.4 Automating Tests with EchoAPI
EchoAPI lets you automate tests. You can write scripts to automatically check if the weather data is correct. This helps make sure your app behaves as expected. For more information, you can refer to ['How to Build a Weather App in VSCode for Beginners(2): Post-response Automate Testing'].
Conclusion
Congratulations! 🎉 You’ve just built a simple weather app from scratch using VSCode and successfully tested it with EchoAPI. Here’s a summary of what you’ve learned:
- Setting up a Node.js project and installing required dependencies.
- Integrating an external weather API into your app.
- Writing clean, structured code to build a web server with Express.
- Testing your API endpoints using EchoAPI.
- This project gives you a solid foundation in API integration, testing, and web app development—key skills for any beginner developer. Now, take it further by adding more features, like weather forecasts or a front-end interface, and explore the endless possibilities!
Top comments (0)