RECENT POST

TOP POST

Free Weather API JSON: How to Build a Weather Forecasting App

by | Jun 16, 2023

In today’s digital age, weather apps have become an essential tool for millions worldwide. Whether planning a weekend getaway, organizing an outdoor event, or simply deciding what to wear, having up-to-date weather information at your fingertips is invaluable. However, building a weather app from scratch might seem daunting. That’s where free weather API JSON comes in.

So, why do we need weather apps? The answer is simple: weather apps provide real-time and accurate weather data. They enable us to make informed decisions based on current and future weather conditions. You’ll need a reliable weather data source to build a weather app. This is where Weatherstack free weather API comes into play.

Weatherstack provides a user-friendly and comprehensive weather API that developers can leverage to fetch weather data for their applications. It offers various endpoints that allow access to different types of weather information.

In this blog post, we will guide you through building a weather app using the Weatherstack API. We’ll cover everything from styling the app to retrieving weather data from Weatherstack and coding the JavaScript. So, let’s dive in and discover the steps to build your weather forecasting app using the Free Weather API JSON and Weatherstack!

free weather api json for accurate weather forecasts & historical data

Is It Reliable to Use APIs for Building a Weather Data App?

Using APIs for building a weather data app is highly reliable and advantageous. APIs provide a structured and standardized way to access and retrieve data from external sources, such as weather data providers.

Here are some reasons why using APIs for building a weather data app is reliable:

  • Weather APIs, like Weatherstack API, connect you to established and reputable weather data providers. These providers collect data from various sources, including meteorological organizations, weather stations, satellites, etc.
  • Weather conditions can change rapidly, and APIs ensure that your app reflects the latest weather updates, including temperature, humidity, wind speed, and more.
  • APIs provide a consistent format and structure for weather data, making it easier for developers to parse and display the information in their app.
  • Reputable weather APIs often provide extensive documentation, including guides, tutorials, and support channels.

Weatherstack API

Weatherstack API is a popular and comprehensive weather data API that provides developers access to accurate and real-time weather information. It offers various features and endpoints to retrieve weather data for various locations worldwide.

It supports HTTP requests and responds with JSON-formatted weather data. Hence, allowing developers to integrate it seamlessly into their applications. Let’s explore the endpoints available at Weatherstack.

Weatherstack for daily historical weather data on weather maps

Endpoints at Weatherstack

Current Weather Data Or Real Time Weather Data

https://api.weatherstack.com/current
    ? access_key = YOUR_ACCESS_KEY
    & query = New York

Historical Weather

https://api.weatherstack.com/historical
    ? access_key = YOUR_ACCESS_KEY
    & query = New York
    & historical_date = 2015-01-21
    & hourly = 1

Historical Time-Series

https://api.weatherstack.com/historical
    ? access_key = YOUR_ACCESS_KEY
    & query = New York
    & historical_date_start = 2015-01-21
    & historical_date_end = 2015-01-25

Weather Forecast

https://api.weatherstack.com/forecast
    ? access_key = YOUR_ACCESS_KEY
    & query = New York
    & forecast_days = 1
    & hourly = 1

Location Lookup for Multiple Locations

https://api.weatherstack.com/autocomplete
    ? access_key = YOUR_ACCESS_KEY
    & query = london

What Are the Steps to Build A Weather App?

Let’s start building our weather forecast data app through Weatherstack API.

Styling The App

We aim to create a simple app with background changes according to the weather conditions. First of all, we create an index.html file with the following template:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Weather app</title>
    <link rel="stylesheet" href="styles.css" />
    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,700;1,600&display=swap" rel="stylesheet">
</head>

<body>
    <div class="container">
        <img src="" alt="" srcset="" id="weather-icon">
        <div id="location">Unable to Fetch Weather</div>
        <div class="desc">No Information Available.</div>
        <div class="weather">
            <div class="c">Error</div>
            <div class="circle"></div>
            <div class="f">Error</div>
        </div>
        <div class="info">
            <h4>Sunrise: <span class="sunrise">No Information Available</span></h4>
            <h4>Sunset: <span class="sunset">No Information Available</span></h4>
        </div>

    </div>
    <script src="scripts.js"></script>
</body>

</html>

We can connect this file to the styles.css file and the js file. Let’s start styling it as under:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  font-family: 'Lora', serif;
}

.container {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  background: rgb(251, 242, 133);
  background: radial-gradient(
    circle,
    rgba(251, 242, 133, 0.6334908963585435) 0%,
    rgba(224, 196, 91, 0.8407738095238095) 35%,
    rgba(230, 224, 113, 1) 100%
  );
}

.weather {
  display: flex; 
  align-items: center;
  margin: 15px 0;
  font-size: 1.5rem;
}

#location {
  font-size: 3rem;
  font-weight: 800;
  font-style: italic;
}
.desc {
  font-size: 1.25rem;
  text-transform: capitalize;
}

.circle {
  background-color: black;
  border-radius: 50px;
  height: 15px;
  width: 15px;
  margin: 0 15px;
}

After the styling part, we move to the API to get the weather data.

Getting Weather Data From Weatherstack

First, you must sign up for a Weatherstack account. Then, you have to generate an API key. Once you get the API key, you must return to your coding process.

Coding the JavaScript

Create a scripts.js file and add a variable “API” that will help us fetch the API key. We will use the following endpoint in our weather forecasting app.

https://api.weatherstack.com/forecast
    ? access_key = YOUR_ACCESS_KEY
    & query = New York
    & forecast_days = 1
    & hourly = 1

The code inside the js file should look like the below:

// Weatherstack API. Do not share it publicly.
const api = '66869939e0b182ac2d6************'; //Replace with your API

const iconImg = document.getElementById('weather-icon');
const loc = document.querySelector('#location');
const tempC = document.querySelector('.c');
const tempF = document.querySelector('.f');
const desc = document.querySelector('.desc');
const sunriseDOM = document.querySelector('.sunrise');
const sunsetDOM = document.querySelector('.sunset');

window.addEventListener('load', () => {
  let long;
  let lat;
  // Accesing Geolocation of User
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      // Storing Longitude and Latitude in variables
      long = position.coords.longitude;
      lat = position.coords.latitude;
      const base = `https://api.weatherstack.com/forecast
    ? access_key = YOUR_ACCESS_KEY
    & query = New York
    & forecast_days = 1
    & hourly = 1`;

      // Using fetch to get data
      fetch(base)
        .then((response) => {
          return response.json();
        })
        .then((data) => {
          const { temp } = data.main;
          const place = data.name;
          const { description, icon } = data.weather[0];
          const { sunrise, sunset } = data.sys;

          const iconUrl = `https://openweathermap.org/img/wn/${icon}@2x.png`;
          const fahrenheit = (temp * 9) / 5 + 32;

          // Converting Epoch(Unix) time to GMT
          const sunriseGMT = new Date(sunrise * 1000);
          const sunsetGMT = new Date(sunset * 1000);

          // Interacting with DOM to show data
          iconImg.src = iconUrl;
          loc.textContent = `${place}`;
          desc.textContent = `${description}`;
          tempC.textContent = `${temp.toFixed(2)} °C`;
          tempF.textContent = `${fahrenheit.toFixed(2)} °F`;
          sunriseDOM.textContent = `${sunriseGMT.toLocaleDateString()}, ${sunriseGMT.toLocaleTimeString()}`;
          sunsetDOM.textContent = `${sunsetGMT.toLocaleDateString()}, ${sunsetGMT.toLocaleTimeString()}`;
        });
    });
  }
});
App to provide historical weather data

Conclusion

By leveraging the power of APIs, like the Weatherstack API, you can create a feature-rich app that provides users with accurate and real-time weather information. Throughout this blog, we have explored the importance of weather apps, the components needed to build an app, the reliability of using APIs, and the steps involved in creating a weather app.

Armed with this knowledge, you are now equipped to embark on your journey to develop a weather forecasting app that keeps users informed and prepared for any weather conditions. Moreover, a Weatherstack API delivers data from accurate global weather models. So, unleash your creativity, and bring your weather app idea to life using the Free Weatherstack API!

FAQs

Is There a Free Weather API?

Yes, free weather APIs, such as OpenWeatherMap, offer access to weather data at no cost. Weatherstack also provides a free plan.

Is There an API for Getting Weather Data?

Several APIs are available for getting weather data, such as Weatherstack, OpenWeatherMap, and AccuWeather.

Which API for Free Historical Weather Data?

Weatherstack API offers free historical weather data, making it a reliable choice for accessing past weather conditions.

Ready to supercharge your weather app? Harness the power of Weatherstack API today!