Vue

Creating a Weather App

Connect to an API using Vue and Axios

Table of Contents
  1. The OpenWeatherMap API
  2. Getting the Weather Data with Axios
  3. Creating the Vue app
  4. Building the Weather App
    1. HTML & CSS
      1. main.css File
      2. index.html file
  5. Vue
    1. Getting API Data with Axios
  6. Conclusion

One of the challenges on freecodecamp is to build a weather app. The idea is pretty simple. Get the weather data from the API provided, build a function to convert the temperature from Celsius to Fahrenheit and show the current weather.

In this article, I'm not going to write a walkthrough on how to solve this challenge fully, but this might be a good start, if you have no clue what to do.

What I am going to show you, is how to use Vue and Axios to connect to the OpenWeatherMap Api, get the weather data from a town(London) and display it.

The OpenWeatherMap API

In order for you to connect to the API you need an API Key, otherwise, the server will just reject your connection attempt.

You can get a free API Key by clicking the subscribe button under the Current Weather Data in this page.

The API will return you the data in JSON format, but you will need to provide a few things in order to get it:

  • The endpoint
  • The API Key
  • The units to get the data (Celsius, Fahrenheit) - defaults to imperial
  • Either the city name, coordinates, zip code or city id

You can check the parameters that the API expects you to pass to get the right JSON data from the documentation page.

In this article, I am declaring metric (Celsius) as the unit and London as the city name. So the API link will look like this:

http://api.openweathermap.org/data/2.5/weather + ?q=London +&?units=metric + &APPID={API KEY}

I have divided the link, so you can see how to add parameters to the API endpoint to get the data that you want.

This is how the API link will look like:

http://api.openweathermap.org/data/2.5/weather?q=London&?units=metric&APPID={API KEY}

If you add your API Key at the end of the link and paste it into your browser, you will get all the data you need. Now, all we have to do, is to get that data into Vue.

Getting the Weather Data with Axios

In Javascript, you can use different tools to get data from an API. In this article, I am using axios. The way you get data from the API doesn't really change much. If you use a different tool you shouldn't have any issues.

To use axios you can either do npm install axios or add the CDN link <script src="https://unpkg.com/axios/dist/axios.min.js"></script> to your page.

In this article I am using axios from the CDN link.

The code that you need to write is pretty straightforward. First, we call axios, then we do a get request from an URL and then we either get a response or catch an error if one is returned.

The code will look like this:

js
1axios
2 .get(url)
3 .then(response => {
4 console.log(response.data);
5})
6 .catch(error => {
7 console.log(error);
8});

If you are wondering why we are getting response.data and not just response, the reason for this is simple. The response will not only return the data, but also status code, headers and the type of request made.

Use the OpenWeatherMap URL and add another console.log(response); and see what you get when you run the code.

Creating the Vue app

I am not going into depth about VueJs or how to create an app with it. But the very quick basics is that you create an app by triggering the Vue object to a div id.

A Vue app looks like this:

js
1let weather = new Vue ({
2 el: "#app",
3 data: {
4
5 },
6 methods: {
7
8 }
9})

The el parameter is the id of the div inside your html. This div id is usually called app but you can name it whatever you wish, just make sure you change el inside the Vue object.

The data parameter contains all the data that you might need for your app, usually, you would create variables here and then use or modify them. This is also where VueJs will try to get the variable names to translate the tags {{name}} in our HTML.

The methods parameter is where you specify all the functions that you might want to call when using the app.

In order to use VueJs you have to install it either with the command, npm install vue or add the CDN link <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> on your page.

I hope this very quick and brief introduction helps you to make sense of things with Vue if you don't know anything about this framework.

Building the Weather App

Now that we have the basic knowledge on how to connect to the OpenWeatherMap API, how to use axios and how to create a Vue app, I will show you how to create the weather app.

HTML & CSS

The HTML for the app will be quite basic. The page will have a background and a centre div with the id="app" that Vue will use. This div will also have a simple background image just to make it look nicer.

So, let's start by creating the HTML code. We will import our css and js files to have a working webpage, we will also import VueJs, axios and the two fonts that we will use in our app.

html
1<!doctype html>
2<html>
3 <head>
4 <meta charset="utf-8">
5 <meta http-equiv="x-ua-compatible" content="ie=edge">
6 <title>Weather App</title>
7 <meta name="viewport" content="width=device-width, initial-scale=1">
8 <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
9 <link href="https://fonts.googleapis.com/css?family=Montserrat:extra-light|Vast+Shadow" rel="stylesheet">
10 </head>
11
12 <body>
13 <div id="app">
14 </div>
15 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
16 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
17 <script src="main.js"></script>
18 </body>
19
20</html>

Now that all the needed files are imported and the page has a title, we will create the skeleton for our div. In order for your data to be displayed, you will use the format {{ variableName }}, this variableName will be the name used within the Vue data in our Vuejs app.

The HTML will be divided into three parts. The left top part that will show the icon, the current weather and the description of the weather. The right top part which will show the min and max temperatures of the day. Finally, the bottom part where we will display other information such as humidity, pressure, the time of the sunrise/sunset and the wind speed.

The <div id="app"> will look like this:

html
1<div id="app">
2 <div id="weather">
3 <img src="images/sunny.svg"> {{overcast}}
4 <span class="temperature">{{currentTemp}}°</span><br>
5 <span id="temp-values">Min {{minTemp}}° <br> Max {{maxTemp}}°</span>
6 </div>
7 <div id="info">
8 <img class="icon" :src=icon> {{sunrise}}
9 <img class="icon" src="images/sunset.svg"> {{sunset}}
10 <img class="icon" src="images/humidity.svg"> {{humidity}}
11 <img class="icon" src="images/pressure.svg"> {{pressure}}
12 <img class="icon" src="images/wind.svg"> {{wind}}
13 </div>

Now that the skeleton of the page is done, we need to update our main.css file in order to have the page look a little bit better.

Note: The code that I am going to show you here isn't responsive and it's a bit hacky. I'm sure there is a better way to do things, but it will do for the purpose of this tutorial.

main.css File

css
1body {
2 background: #3d4869; /* Old browsers */
3 background: -moz-linear-gradient(#3d4869, #263048) fixed; /* FF3.6-15 */
4 background: -webkit-linear-gradient(#3d4869,#263048) fixed; /* Chrome10-25,Safari5.1-6 */
5 background: linear-gradient(#3d4869,#263048) fixed; /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
6 background-repeat: no-repeat;
7
8 font-family: 'Montserrat', sans-serif;
9 font-weight: 100;
10 text-shadow: 0px 0px 2px #000000;
11 color: #ffffff;
12}
13
14#app {
15 background: url(images/waves.svg) no-repeat;
16
17 width: 520px;
18 height: 170px;
19
20 position: absolute;
21 top: 35%;
22 left: 35%;
23}
24
25#weather {
26 padding: 15px;
27 vertical-align: middle;
28}
29
30.temperature {
31 font-family: 'Vast Shadow', cursive;
32 font-size: 40px;
33 vertical-align: top;
34 position: absolute;
35 left: 80px;
36}
37
38#temp-values {
39 text-align: right;
40 text-justify: distribute;
41 display: block;
42 position: relative;
43 top: -60px;
44}
45
46#info {
47 padding-left: 20px;
48 position: relative;
49 top: -20px;
50}
51
52.icon {
53 position: inherit;
54 top: 2px;
55 padding-left: 8px;
56}

index.html file

html
1<!doctype html>
2<html>
3 <head>
4 <meta charset="utf-8">
5 <meta http-equiv="x-ua-compatible" content="ie=edge">
6 <title>Weather App</title>
7 <meta name="viewport" content="width=device-width, initial-scale=1">
8 <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
9 <link href="https://fonts.googleapis.com/css?family=Montserrat:extra-light|Vast+Shadow" rel="stylesheet">
10 </head>
11
12 <body>
13 <div id="app">
14 <div id="weather">
15 <img src="images/sunny.svg"> {{overcast}}
16 <span class="temperature">{{currentTemp}}°</span><br>
17 <span id="temp-values">Min {{minTemp}}° <br> Max {{maxTemp}}°</span>
18 </div>
19 <div id="info">
20 <img class="icon" :src=icon> {{sunrise}}
21 <img class="icon" src="images/sunset.svg"> {{sunset}}
22 <img class="icon" src="images/humidity.svg"> {{humidity}}
23 <img class="icon" src="images/pressure.svg"> {{pressure}}
24 <img class="icon" src="images/wind.svg"> {{wind}}
25 </div>
26 </div>
27 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
28 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
29 <script src="main.js"></script>
30 </body>
31</html>

If you try to open the page you will notice that the app doesn't look that great at the moment, that's because we don't have Vue doing the heavy lifting for us. Let's go ahead and fix this.

Note: that I'm using SVG files for the weather app background and icons, you can get the files here.

Vue

Vue and axios are already imported through the script tag located in our html code, what means that we are ready to start giving shape to our app.

js
1let weatherApp = new Vue ({
2 el: '#app',
3 data: {
4
5 },
6 methods: {
7 getWeather() {
8 },
9 }
10 beforeMount() {
11 this.getWeather();
12 }
13});

The code will be pretty straightforward, we initiate a new Vue app attached to the div with the id app. Inside the Vue app, we declare all the needed variables inside the data object, these variables will be the ones we will use to populate with the information obtained through the API.

Also, we declare a method called getWeather, this is the method that will use axios to get all the information we need from the OpenWeatherMap API.

We want the weather app to show the current weather and other weather information such as:

  • Minimum temperature for the day
  • Maximum temperature for the day
  • Sunset time
  • Sunrise time
  • Wind speed
  • Pressure
  • Humidity percentage

The API will return all of these details so we don't need to do much. Inside our Vue object, we will declare all the variables that we need to update the tags ({{variableName}}) in our HTML, once we connect to the API and get the needed data.

The data object inside our VueJs will look like this:

js
1data: {
2 currentTemp: '',
3 minTemp: '',
4 maxTemp: '',
5 sunrise: '',
6 sunset:'',
7 pressure: '',
8 humidity: '',
9 wind: '',
10 overcast: '',
11 icon: ''
12 },

Getting API Data with Axios

The OpenWeatherMap API returns a JSON response that looks like this:

json
1{
2 "coord": {
3 "lon": -0.13,
4 "lat": 51.51
5 },
6 "weather": [
7 {
8 "id": 803,
9 "main": "Clouds",
10 "description": "broken clouds",
11 "icon": "04d"
12 }
13 ],
14 "base": "stations",
15 "main": {
16 "temp": 24.82,
17 "pressure": 1016,
18 "humidity": 51,
19 "temp_min": 23,
20 "temp_max": 27
21 },
22 "visibility": 10000,
23 "wind": {
24 "speed": 8.2,
25 "deg": 270
26 },
27 "clouds": {
28 "all": 75
29 },
30 "dt": 1534695600,
31 "sys": {
32 "type": 1,
33 "id": 5091,
34 "message": 0.003,
35 "country": "GB",
36 "sunrise": 1534654394,
37 "sunset": 1534706018
38 },
39 "id": 2643743,
40 "name": "London",
41 "cod": 200
42}

We are going to use our earlier example of axios to build the getWeather method of our Vue app. This method will look like this:

js
1getWeather() {
2 let url = "http://api.openweathermap.org/data/2.5/weather?q=London&?units=metric&APPID={API KEY}";
3 axios
4 .get(url)
5 .then(response => {
6 this.currentTemp = response.data.main.temp;
7 this.minTemp = response.data.main.temp_min;
8 this.maxTemp = response.data.main.temp_max;
9 this.pressure = response.data.main.pressure;
10 this.humidity = response.data.main.humidity + '%';
11 this.wind = response.data.wind.speed + 'm/s';
12 this.overcast = response.data.weather[0].description;
13 this.icon = "images/" + response.data.weather[0].icon.slice(0, 2) + ".svg";
14 this.sunrise = new Date(response.data.sys.sunrise*1000).toLocaleTimeString("en-GB").slice(0,4);
15 this.sunset = new Date(response.data.sys.sunset*1000).toLocaleTimeString("en-GB").slice(0,4);
16 })
17 .catch(error => {
18 console.log(error);
19 })
20}

As you can see by the JSON response that we get from the API, the above code is simply assigning each bit of data retrieved from the API to the variables declared in the data object in Vue, this will allow us to use the data everywhere in the app.

Notice that we are adding something to some variables.

In the icon variable we add the path for the images folder, the file name and file extension. When Vue runs it will change the src of the image to whatever the value inside icon is.

For the file name, we will slice the string that we get from the API from the char located on index 0 up to char at index 2 - this is because OpenWeatherMap changes the icon name depending on if it is day or night.

The sunrise and sunset times are given in Unix epoch time, so we just convert the time to a human-readable format and then slice the string in order to get only the hours and minutes.

Your main.js file and the Vue app should look like this now:

js
1let weatherApp = new Vue({
2 el: '#app',
3 data: {
4 currentTemp: '',
5 minTemp: '',
6 maxTemp:'',
7 sunrise: '',
8 sunset: '',
9 pressure: '',
10 humidity: '',
11 wind: '',
12 overcast: '',
13 icon: ''
14 },
15 methods: {
16 getWeather() {
17 let url = "http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&APPID={Your API Key}";
18 axios
19 .get(url)
20 .then(response => {
21 this.currentTemp = response.data.main.temp;
22 this.minTemp = response.data.main.temp_min;
23 this.maxTemp = response.data.main.temp_max;
24 this.pressure = response.data.main.pressure;
25 this.humidity = response.data.main.humidity + '%';
26 this.wind = response.data.wind.speed + 'm/s';
27 this.overcast = response.data.weather[0].description;
28 this.icon = "images/" + response.data.weather[0].icon.slice(0, 2) + ".svg";
29 this.sunrise = new Date(response.data.sys.sunrise*1000).toLocaleTimeString("en-GB").slice(0,4);
30 this.sunset = new Date(response.data.sys.sunset*1000).toLocaleTimeString("en-GB").slice(0,4);
31 })
32 .catch(error => {
33 console.log(error);
34 });
35 },
36 },
37 beforeMount() {
38 this.getWeather();
39 },
40});

Replace {Your API Key} with the API key that you obtained from OpenWeatherMap and reload the page, you should see the app with the current weather data now.

Conclusion

This post was rather long, I would like to first thank you for sticking up with it. I hope you learned how to use axios and Vue together to get data from an API. I would like now to ask you if you would like something to be explained more clearly or if you would like me to explain something else.

Finally, what was the first thing you created by using an API?

Webmentions

0 Like 0 Comment

You might also like these

Learn how to implement HTML5 Geolocation API and VueJs together to get the current location of an user.

Read More
Vue

Weather App - Using geolocation and Vue

Weather App - Using geolocation and Vue

Exploration on how to run Pyscript in a React (NextJS) app, this article explores issues and solutions to run PyScript in a React app.

Read More
PyScript

How to run PyScript in React

How to run PyScript in React

How to create a function to filter articles by tag. On this post I am using the javascript filter method to filter all articles.

Read More
React

How to filter all MDX articles by tags

How to filter all MDX articles by tags

A quick introduction on how to use the Elasticlurn Plugin for Gatsby together with MDX to create a search bar component and allow users to search your site.

Read More
React

How to use elasticlunr plugin with MDX

How to use elasticlunr plugin with MDX