How to use external API to build a weather app in JavaScript

Hamza Masood
7 min readApr 28, 2021

--

In this tutorial, we’ll learn how to build a simple weather app, with JavaScript with the help of API. We have a lot of interesting things to cover here.

Step 1: Find a weather API

First of all, we have to find a provider that will let us incorporate its weather data into our app. Several providers provide API services for developing weather apps. Most of them include a free package along with premium subscriptions that scale depending on the services/features. For this project, I choose AccuWeather APIs. After signing up go to MY APPS and click on +add new App button.

To choose your plan and click on Create App.

After creating app click on app name in my case “weatherapp” you will get API key and other information:-

We have successfully got our API key, here Step 1 is completed.

(Note: you should use your own apikey. )

Now let’s start coding.

To build this app I used VS Code as a code editor. Create a project folder to keep your all files in one place, and then open that folder in VS Code or you can open VS Code first and then create a new folder and create the following files:-

  • index.html
  • css/style.css
  • js/app.js
  • js/forcast.js
  • img (click here to get project images)

Step 2: UI design

Now it's time to build our user interface. In this app, I have designed a very simple UI because the main purpose of this tutorial is to guide you on how to use APIs. I didn’t bother to put a lot of CSS for styling, to keep my app simple I used Bootstrap.

The UI contains only one input to get the city name from user, and a card to display the weather results.

index.html

Open index.html and add basic HTML code:-

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body></body></html>

Add Bootstrap CSS link in the head section to get the benefits of Bootstrap.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

also add local CSS file link for our custom styling.

<link rel="stylesheet" href="css/style.css">

Now using Bootstrap make basic page Skelton in body

<div class="container my-5"><div class="row"><div class="col-md-4 offset-md-4 text-center"><h1>Weather app</h1><!-- our UI code goes here --><div id="details" class="card my-5 d-none"></div></div></div></div>

Now we will add our UI code in between the above code. Firstly we will put a form to get City input from user.

<form class="form-group"><label for="city">Enter a location for Weather Information</label><input type="text" name="city" class="form-control"></form>

Then we will put a card wich will display City weather report (later we will convert this code to dynamic)

<div id="details" class="card my-5 d-none"><!-- Image for day/night --><img src="img/day.svg" class="card-img-top"><div class="icon mx-auto bg-light"><img src="img/icons/1.svg"></div><!-- Weather details --><div class="text-muted text-uppercase"><h4 class="my-1">NEW YORK</h4><h5 class="my-1">(NEW YORK)</h5><h6>UNITED STATES</h6><div class="mt-3">CLOUDY</div><div class="display-4 my-2"><span>13.3</span><span>&deg;C</span></div></div></div>

Add this code in style.css to change page background and formating weather icon

body{background: #ddd;}.icon{margin-top: -50px;border-radius: 50%;}

Now we have done with our UI.

Step 3: Get Weather Forcast with API

We have finished our UI design, let’s start working on API to get the Weather forecast.

Open AccuWeather page and open API Reference page.

(Note: you should use your own apikey. )

Now open Locations API, and scroll down to Text Search and click on City Search.

You will find here the Resource URL which will help us to find the city. Resource URL take two parameters an “apikey” and “q”. In apikey we will pass our apikey, and in q we will pass the city name.

forcast.js

Open forcast.js and first of all, we will save our API key in a local variable for later use. (remember we get this key from the My Apps page)

(Note: you should use your own apikey. )

apikey = "your api key";

Now we will code a function to get the city information.

const getCity = async (city) => {const baseUrl ="https://dataservice.accuweather.com/locations/v1/cities/search";const queryParameters = `?apikey=${apikey}&q=${city}`;const response = await fetch(baseUrl + queryParameters);const data = await response.json();return data[0];};

If we console.log() the result of the above function, it will return us an object of a city that contains a lot of information, we will use this information later in our app.

From the above, we need the Key which will help us to get the weather information of the current city. Now we use another function that will get city weather information on the base of that Key.

const getWeather = async (locationKey) => {const baseUrl = "https://dataservice.accuweather.com/currentconditions/v1/";const queryParameters = `${locationKey}?apikey=${apikey}`;const response = await fetch(baseUrl + queryParameters);const data = await response.json();return data[0];};

If we console.log() the result of the above function, it will return us following weather information about the city.

Now our API functioning is complete, we have successfully get weather information. It's time to connect these results with our UI design, so lets move to the next session.

Step 4: Connect API Results with UI

Now we will connect our API results (weather information) with our UI, for this purpose we will work on app.js.

app.js

Open app.js and lets start our code to get our API results on UI.

First of all, we will grab our city form.

const cityForm = document.querySelector("form");

Now we will add an event listener on the form submit.

cityForm.addEventListener("submit", (e) => {e.preventDefault();
const city = cityForm.city.value.trim();cityForm.reset();updateCity(city).then((data) => updateUI(data)).catch((err) => {alert("Something went wrong, please try later");console.log(err);throw new Error("Please enter the correct city name");});});

in the above event listener, we call a function updateCity() which is taking the city as an argument. the updateCity() function will call getCity() and getWeather() functions to get data from API and on success it will call another function updateUI() which will take data as an argument and return us the updated UI with city weather information.

const updateCity = async (city) => {const cityDetails = await getCity(city);const cityWeather = await getWeather(cityDetails.Key);return { cityDetails, cityWeather };};

Now we will move the innerHTML of card from index.html to the following updateUI() function, which will dynamically update the card.

const card = document.querySelector(".card");const updateUI = (data) => {const { cityDetails, cityWeather } = data;card.innerHTML = `<!-- Image for day/night --><img src="img/${cityWeather.IsDayTime ? "day.svg" : "night.svg"}" class="card-img-top"><div class="icon mx-auto bg-light"><img src="img/icons/${cityWeather.WeatherIcon}.svg"></div><!-- Weather details --><div class="text-muted text-uppercase"><h4 class="my-1">${cityDetails.EnglishName}</h4><h5 class="my-1">(${cityDetails.AdministrativeArea.EnglishName})</h5><h6>${cityDetails.Country.EnglishName}</h6><div class="mt-3">${cityWeather.WeatherText}</div><div class="display-4 my-2"><span>${cityWeather.Temperature.Metric.Value}</span><span>&deg;C</span></div></div>`;};

The weather app is ready

Hurrah!!! we have successfully completed our simple weather app. I hope that you enjoyed it and that it has helped enhance your API knowledge.

You can get complete code on my github. Feel free to contact me.

Once again, don’t forget to put your own key for live app testing!

Thanks for reading.

As always, thanks a lot for reading!

Next Steps

There are so many things that you can do to extend the functionality of this weather app. Here are some thoughts:

  • Use localStorage to persist the data above or even a real-time database like Firebase.

If there’s anything else that you might want to see as an app extension, let me know in the comments below!

--

--

Hamza Masood
Hamza Masood

No responses yet