Implementation of OpenWeather API
❗ Did you notice the background color change? ❗
The weather data in the box below is being fetched from the OpenWeather API. The background color of this webpage is dynamic; it is based on the received temperature data at the time the page loads.
Varying shades of blue represent ranges of cold temperatures, while varying shades of red represent ranges of hot temperatures. If you have a green/yellow background, the temperature is just right.
Current Weather in Seattle, WA
Application created by Mike Shine
Tutorial: How to use OpenWeather API
Curious about how to make one of your own? Follow along with the tutorial.
Note: Some intermediate knowledge of HTML, inline CSS, JavaScript, and jQuery is needed.
OpenWeather.com / getting your API key
To get your API key, follow these two steps:
- Sign up for a free account at OpenWeather. Your key will be generated and available for your use after you sign up.
- Open the API documentation in another tab for later reference.
Code part one – HTML
Step 1 – Create a new .html file, and use the following code as a starting point:
<html>
<head>
<meta charset="utf-8">
<title>OpenWeather API</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Cardo&display=swap" rel="stylesheet">
</head>
<body>
<h1>Today's weather in Seattle</h1>
<link>
tags are optional. I only include them to match the font on my website.Step 2– Edit the last line of code (the <h1>
) to reflect your location.
Code part two – JavaScript
All of this JavaScript code is written inside the same .html file as above, inside <script>
tags.
Step 3– Add the following code:
<script>
let settings = {
"async": true,
"crossDomain": true,
"url": "https://api.openweathermap.org/data/2.5/weather?zip={YOUR_ZIPCODE_HERE}&units=imperial&appid={YOUR_API_KEY_HERE}",
"method": "GET",
};
</script>
This code sets up the API request.Step 4– Replace YOUR_ZIPCODE_HERE and YOUR_API_KEY_HERE with your zipcode and API key, respectively.
Code part three – HTML
Step 5– Add this HTML code:
<script>
$.ajax(settings).done(function (response) {
var temperature = response.main.temp;
$("#mainTemp").append(content);
</script>
This code extracts the data you want from the API (ajax) response and displays it on the DOM.The main.temp part of the expression can be replaced with any parameter you wish (see chart below).
The #mainTemp id should be changed along with the main.temp parameter to something unique.
Step 6– Check out the table below to see some of the response data we can receive from our API call:
Element | JSON Path | Description | Data type | Notes |
---|---|---|---|---|
Temperature | main.temp | The temperature of the queried location. | float | Unit is Farenheit |
Weather description | weather[0].description | A brief summary of the forecasted weather conditions. | string | |
Low temperature | main.temp_min | The minimum possible temperature at the moment. | float | Unit is Farenheit |
High temperature | main.temp_max | The maximum possible temperature at the moment. | float | Unit is Farenheit |
Humidity | main.humidity | The current humidity. | float | Unit is a percentage |
Wind speed | wind.speed | The current wind speed. | float | Unit is miles per hour |
<script>
$.ajax(settings).done(function (response) {
var content = response.main.temp;
$("#mainTemp").append(content);
});
$.ajax(settings).done(function (response) {
var content = response.main.humidity;
$("#humidity").append(content);
});
$.ajax(settings).done(function (response) {
var content = response.weather[0].description;
$("#description").append(content);
});
$.ajax(settings).done(function (response) {
var content = response.wind.speed;
$("#windSpeed").append(content);
});
</script>
<div id="mainTemp">Current temperature (°F): </div>
<div id="humidity">Humidity (%): </div>
<div id="description">Forecast: </div>
<div id="windSpeed">Wind speed (mph): </div>
Each of the $.ajax
snippets extracts the data from the API response, which is then displayed on the corresponding <div>
line below.Step 7– Customize your code with any of the weather options detailed in the table above, or go to this page on OpenWeather to see the full JSON response object.
(Optional) Code part 4 – Changing background color
The changing background color feature has nothing to do with the API or JSON – I just did it for fun.
If you want to see how I did it and add it to your version, read this section. If you are just here for the APIs, you can skip ahead to the Conclusion section.
Step 8– Add this jQuery/JavaScript code script to your code:
<script>
$.fn.weatherColor = function(temp) {
if (temp < 0) {
this.css("background", "linear-gradient(to right, #07071f, darkblue)")
} else if (temp >= 0 && temp < 15) {
this.css("background", "linear-gradient(to right, darkblue, darkslateblue)")
} else if (temp >= 15 && temp < 30) {
this.css("background", "linear-gradient(to right, navy, royalblue)")
} else if (temp >= 30 && temp < 45) {
this.css("background", "linear-gradient(to right, dodgerblue, deepskyblue)")
} else if (temp >= 45 && temp < 59) {
this.css("background", "linear-gradient(to right, skyblue, lightskyblue)")
} else if (temp >= 59 && temp < 70) {
this.css("background", "linear-gradient(to right, paleturquoise, lemonchiffon)")
} else if (temp >= 70 && temp < 75) {
this.css("background", "linear-gradient(to right, wheat, sandybrown)")
} else if (temp >= 75 && temp < 81) {
this.css("background", "linear-gradient(to right, lightsalmon, coral)")
} else if (temp >= 81 && temp < 88) {
this.css("background", "linear-gradient(to right, tomato, orangered)")
} else if (temp >= 88 && temp < 93) {
this.css("background", "linear-gradient(to right, indianred, crimson)")
} else if (temp >= 93) {
this.css("background", "linear-gradient(to right, firebrick, darkred)")
}
}
</script>
This function takes in a number (the temperature) as an argument, and changes the background color of the page based on which temperature range it belongs to.
There's only one step left, which is to run the function when the temperature data is received. To do this, you will need to add one line of code to a script you made previously.
<script>
$.ajax(settings).done(function (response) {
var content = response.main.temp;
$("#mainTemp").append(content);
$(document.body).weatherColor(Number(content))
});
$.ajax(settings).done(function (response) {
var content = response.main.humidity;
$("#humidity").append(content);
});
$.ajax(settings).done(function (response) {
var content = response.weather[0].description;
$("#description").append(content);
});
$.ajax(settings).done(function (response) {
var content = response.wind.speed;
$("#windSpeed").append(content);
});
</script>
<div id="mainTemp">Current temperature (°F): </div>
<div id="humidity">Humidity (%): </div>
<div id="description">Forecast: </div>
<div id="windSpeed">Wind speed (mph): </div>
Finishing touches
Step 9– When you are done, close off your html file by adding this to the end:
</body>
</html>
If you are experiencing any issues, compare your code to my complete code for this API implementation:
<h3>Current Weather in Seattle, WA</h3>
<script>
let settings = {
"async": true,
"crossDomain": true,
"url": "https://api.openweathermap.org/data/2.5/weather?zip=98122&units=imperial&appid=7f944555d8ad32f1ca731f0076de5e64",
"method": "GET",
};
</script>
<script>
$.ajax(settings).done(function (response) {
var content = response.main.temp;
$("#mainTemp").append(content);
$(document.body).weatherColor(Number(content))
});
$.ajax(settings).done(function (response) {
var content = response.main.humidity;
$("#humidity").append(content);
});
$.ajax(settings).done(function (response) {
var content = response.weather[0].description;
$("#description").append(content);
});
$.ajax(settings).done(function (response) {
var content = response.wind.speed;
$("#windSpeed").append(content);
});
</script>
<script>
$.fn.weatherColor = function(temp) {
if (temp < 0) {
this.css("background", "linear-gradient(to right, #07071f, darkblue)")
} else if (temp >= 0 && temp < 15) {
this.css("background", "linear-gradient(to right, darkblue, darkslateblue)")
} else if (temp >= 15 && temp < 30) {
this.css("background", "linear-gradient(to right, navy, royalblue)")
} else if (temp >= 30 && temp < 45) {
this.css("background", "linear-gradient(to right, dodgerblue, deepskyblue)")
} else if (temp >= 45 && temp < 59) {
this.css("background", "linear-gradient(to right, skyblue, lightskyblue)")
} else if (temp >= 59 && temp < 70) {
this.css("background", "linear-gradient(to right, paleturquoise, lemonchiffon)")
} else if (temp >= 70 && temp < 75) {
this.css("background", "linear-gradient(to right, wheat, sandybrown)")
} else if (temp >= 75 && temp < 81) {
this.css("background", "linear-gradient(to right, lightsalmon, coral)")
} else if (temp >= 81 && temp < 88) {
this.css("background", "linear-gradient(to right, tomato, orangered)")
} else if (temp >= 88 && temp < 93) {
this.css("background", "linear-gradient(to right, indianred, crimson)")
} else if (temp >= 93) {
this.css("background", "linear-gradient(to right, firebrick, darkred)")
}
}
</script>
<div id="mainTemp">Current temperature (°F): </div>
<div id="humidity">Humidity (%): </div>
<div id="description">Forecast: </div>
<div id="windSpeed">Wind speed (mph): </div>
Be sure to check out all the other ways to fetch weather with the OpenWeather API! It's a robust API with lots of functionality. Click here to see more ways to structure an API call with OpenWeather.
Attribution: Although I had previously built a forecast-fetching web app using the OpenWeather API, it occurred to me only recently to create a slightly simpler version with a tutorial. Credit for the idea should go to Aaron Redshaw, an outstanding technical writer whose website I happened upon recently. Please check out Aaron's website here!