Overview
Creating a simple weather web app involves getting information from api and displaying it to the users accordingly.
The main aim for this blog is to tell more about fetch API concept in JS using RapidAPI.
This what our project would look at the end
Before we move on, it'll be better if we first understood what is an API anyways?
API
An API(Application Program Interface) is a set of rules and protocols for building and interacting with software applications. It allows different software systems to communicate with each other.
Though their are many 3 types of API:
Web API accessed across the internet using HTTP/HTTPS protocols. (that's what we're gonna use.)
Library API integrated into software library and are used to interact with functionalities provided with library.
Operating System API provides functionalities for interacting with Os's core.
What is RapidAPI and Why are we using it ?
First let's answer, "what is RapidAPI?"
RapidAPI is a platform that provides developers with a single, centralized place to find connect to, and manage APIs. It simplifies the process of integrating third-party APIs into applications, offering a wide variety of APIs across different categories and use cases.
And Why we're gonna use it anyways, when there're already many out there, what makes it standout?
Though RapidAPI offers several advantages that make it a superior choice for developers when it comes to API integration and management.
Here are some reason why?
Comprehensive API Marketplace, i.e. RapidAPI hosts various API from all categories, it allows developers find their API exact to their project.
Ease of Integration, RapidAPI generates ready-to-use code snippets in various programming languages, (JavaScript, Python, Ruby).
And the list goes on, but the above reasons would be benefiting us for this project.
This what the page of RapidAPI looks like as of the year of this blog post
First Step to make our Weather Web App, writing the HTML
The HTML for our project would be very simple, as we'll be focusing more on the FETCH API concept in JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Merriweather:ital,wght@0,300;0,400;0,700;0,900;1,300;1,400;1,700;1,900&display=swap" rel="stylesheet">
<title>Weather App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Weather App</h1>
<input type="search" class="city_search" placeholder="search city...">
<button class="search_btn" type="submit">search</button>
<div class="weather_info">
<h2 class="loc"></h2>
<p class="max_temp"></p>
<p class="min_temp"></p>
<p class="humidity %"></p>
</div>
</div>
</body>
<script src="script.js"></script>
</html>
Let me just provide you a quick overview for the above code.
*The two links that you see at first:
*
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Merriweather:ital,wght@0,300;0,400;0,700;0,900;1,300;1,400;1,700;1,900&display=swap" rel="stylesheet">
These are just the fonts that I chose for the project, here's the link for that, Font for the Project
The basic structure of our project.
HTML Structure
1. **Body Tag**
-
<body>
: The body tag contains all the content of the HTML document that will be visible to the user.
2. **Container Div**
-
<div class="container">
: This div acts as a container for the entire weather app. It helps to group all related elements together and can be styled as a single unit.
3. **Header
- **<h1>Weather App</h1>
: This is the main heading of the web page, indicating the purpose of the app.
4. **City Search Input**
-
<input type="search" class="city_search" placeholder="search city...">
:- Type: The input type is "search", which is specifically designed for search fields.
- Class: The class "city_search" can be used to apply CSS styles and JavaScript functionality to this element.
- Placeholder: The placeholder text "search city..." is displayed inside the input field when it is empty, guiding the user on what to input.
5. **Search Button**
-
<button class="search_btn" type="submit">search</button>
:- Type: The button type is "submit", which generally indicates that it will submit a form. However, in this context, it is likely used to trigger a JavaScript function to fetch weather data.
- Class: The class "search_btn" can be used to style the button and attach event listeners in JavaScript.
- Text: The button displays the text "search".
6. **Weather Information Display
- **<div class="weather_info">
: This div groups together all the elements that will display the weather information for the searched city.
-
Location Heading:
-
<h2 class="loc"></h2>
: An empty heading with the class "loc" where the name of the location (city) will be inserted dynamically.
-
-
Max Temperature Paragraph:
-
<p class="max_temp"></p>
: An empty paragraph with the class "max_temp" where the maximum temperature will be displayed.
-
-
Min Temperature Paragraph:
-
<p class="min_temp"></p>
: An empty paragraph with the class "min_temp" where the minimum temperature will be displayed.
-
-
Humidity Paragraph:
-
<p class="humidity %"></p>
: An empty paragraph with the class "humidity %" where the humidity percentage will be displayed.
-
This HTML structure sets up a basic user interface for a weather app. It includes:
- A heading that indicates the app's purpose.
- An input field for users to search for a city.
- A button to initiate the search for weather data.
- A section to display the weather information (location, max temperature, min temperature, and humidity).
Styling our Project (CSS)
body{
margin: 0;
padding: 0;
background-image: url(bg.jpg);
background-repeat: none;
background-size: 1372px;
font-family: "Merriweather", serif;
font-weight: 700;
font-style: normal;
}
.container{
display: block;
background-color: rgba(255, 255, 255, 0.349);
width: 500px;
height: 350px;
border-radius: 12px;
position: absolute;
top: 20%;
left: 30%;
}
h1{
position: relative;
left: 30%;
}
.city_search{
position: relative;
left: 25%;
margin: 5px;
padding: 12px;
border: none;
border-radius: 5px;
width: 220px;
font-weight: 750;
}
.search_btn{
position: relative;
left: 25%;
margin: 5px;
padding: 12px;
width: 65px;
border: none;
border-radius: 7px;
font-family: 750;
}
.search_btn:hover{
background-color: gray;
}
.city_search:hover{
background-color: rgb(173, 173, 173);
}
.weather_info{
position: absolute;
left: 25%;
bottom: 10%;
width: 250px;
}
.weather_info h2 p{
margin: 12px;
padding: 12px;
}
These are the basic CSS used to just make our project look a little better, you could of course change it according to our taste.
JS
let citySearch = document.querySelector(".city_search");
let maxtemp = document.querySelector(".max_temp");
let mintemp = document.querySelector(".min_temp");
let humid = document.querySelector(".humidity");
let search_btn = document.querySelector(".search_btn");
let city_name = document.querySelector(".loc");
const fetchWeather = async() => {
const loca = citySearch.value.trim();
if(loca == ""){
alert("please enter a city name!");
return;
}
console.log(loca);
const url = `https://weather-by-api-ninjas.p.rapidapi.com/v1/weather?city=${loca}`;
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'd0a761a10cmshbbd424015a9e586p183e49jsnd47327b28327',
'X-RapidAPI-Host': 'weather-by-api-ninjas.p.rapidapi.com'
}
};
try {
const response = await fetch(url, options);
const result = await response.json();
console.log(result);
const max_temp = result.max_temp;
const min_temp = result.min_temp;
const humidity = result.humidity;
city_name.textContent = `Location: ${loca}`;
maxtemp.textContent = `Max Temp: ${max_temp} C`;
mintemp.textContent = `Min Temp: ${min_temp} C`;
humid.textContent = `Humidity: ${humidity} %`;
} catch (error) {
console.error(error);
}
}
search_btn.addEventListener("click",fetchWeather);
Now, before we move on, lets understand how to setup RapidAPI client.
Step 1: Install RapidAPI Client from VSCODE Extensions.
search for RapidAPI Client in extensions and install the RapidAPI Client
Step 2: Make your account on RapidAPI
Setp 3: search for Weather APIs by API Ninja
Although you can find other api as well, I chose this one for it's Freemium feature on it.
Step 4: Subscribe to according to your need, don't worry as mentioned it has free feature with a lot a usage!!
Step 5: Integrate the API with your code.
You'll see the code snippet at the right side of the panel.
Step 6:Copy the code and paste it that fits to your project, here this is where i have used it.
const url = `https://weather-by-api-ninjas.p.rapidapi.com/v1/weather?city=${loca}`;
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'd0a761a10cmshbbd424015a9e586p183e49jsnd47327b28327',
'X-RapidAPI-Host': 'weather-by-api-ninjas.p.rapidapi.com'
}
};
try {
const response = await fetch(url, options);
const result = await response.json();
console.log(result);
const max_temp = result.max_temp;
const min_temp = result.min_temp;
const humidity = result.humidity;
city_name.textContent = `Location: ${loca}`;
maxtemp.textContent = `Max Temp: ${max_temp} C`;
mintemp.textContent = `Min Temp: ${min_temp} C`;
humid.textContent = `Humidity: ${humidity} %`;
} catch (error) {
console.error(error);
}
the further for this is explained down below.
Variable Declarations
let citySearch = document.querySelector(".city_search");
let maxtemp = document.querySelector(".max_temp");
let mintemp = document.querySelector(".min_temp");
let humid = document.querySelector(".humidity");
let search_btn = document.querySelector(".search_btn");
let city_name = document.querySelector(".loc");
-
citySearch
: Selects the input element where the user will type the city name, using the class selector.city_search
. -
maxtemp
: Selects the element that will display the maximum temperature, using the class selector.max_temp
. -
mintemp
: Selects the element that will display the minimum temperature, using the class selector.min_temp
. -
humid
: Selects the element that will display the humidity, using the class selector.humidity
. -
search_btn
: Selects the button that the user will click to search for the weather, using the class selector.search_btn
. -
city_name
: Selects the element that will display the location name, using the class selector.loc
.
Fetch Weather Function
const fetchWeather = async() => {
const loca = citySearch.value.trim();
if(loca == ""){
alert("please enter a city name!");
return;
}
console.log(loca);
-
fetchWeather
: Declares an asynchronous function to fetch weather data. -
loca
: Retrieves the value from thecitySearch
input field, and trims any leading or trailing whitespace. -
Check if
loca
is empty: If the input field is empty, an alert is shown to prompt the user to enter a city name and the function returns early. -
console.log(loca)
: Logs the city name to the console for debugging purposes.
API Request Setup
const url = `https://weather-by-api-ninjas.p.rapidapi.com/v1/weather?city=${loca}`;
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'd0a761a10cmshbbd424015a9e586p183e49jsnd47327b28327',
'X-RapidAPI-Host': 'weather-by-api-ninjas.p.rapidapi.com'
}
};
-
url
: Constructs the API URL, inserting the city name (loca
) into the query string. -
options
: Defines the options for the fetch request, including the HTTP method (GET
) and the necessary headers for authentication:-
'X-RapidAPI-Key'
: Your unique API key for authentication. -
'X-RapidAPI-Host'
: The host for the API.
-
Fetch Weather Data
try {
const response = await fetch(url, options);
const result = await response.json();
console.log(result);
-
try
block: Wraps the fetch request in a try-catch block to handle potential errors. -
response
: Awaits the fetch request to the API URL with the specified options. -
result
: Awaits the response to be converted to JSON format. -
console.log(result)
: Logs the JSON response to the console for debugging.
Process and Display Weather Data
const max_temp = result.max_temp;
const min_temp = result.min_temp;
const humidity = result.humidity;
city_name.textContent = `Location: ${loca}`;
maxtemp.textContent = `Max Temp: ${max_temp} C`;
mintemp.textContent = `Min Temp: ${min_temp} C`;
humid.textContent = `Humidity: ${humidity} %`;
} catch (error) {
console.error(error);
}
}
-
Extract Data: Retrieves the
max_temp
,min_temp
, andhumidity
properties from theresult
object. -
Update DOM:
-
city_name.textContent
: Sets the text content of the location element to display the city name. -
maxtemp.textContent
: Sets the text content of the max temperature element. -
mintemp.textContent
: Sets the text content of the min temperature element. -
humid.textContent
: Sets the text content of the humidity element.
-
-
catch
block: Catches any errors that occur during the fetch request or data processing and logs the error to the console.
Event Listener
search_btn.addEventListener("click", fetchWeather);
-
Add Event Listener: Attaches a click event listener to the search button. When the button is clicked, it triggers the
fetchWeather
function to execute.
Conclusion
At last I want to say is that blog was to give you a brief intro on how to use the RapidAPI, that helps you make your project build better and faster.
Thank You.
Top comments (0)