JavaScript weather app for absolute beginners
Tags: javascript, beginners, webdev, tutorial
Published: 2021-11-12 07:56:39

##Introduction
I know, calling APIs and fetching them can be really tough for beginners. It is an absolute pain in the neck for absolute beginners. However, I'll try to explain all about APIs through a really decent web application, a simple weather app.

This may seem tough, but actually it's easier than it looks. 

I will be using AJAX to call APIs and fetch information from them, so this might seem outdated, but to get a good idea about API calling, this is a good way to start.

You need to know some Javascript to continue with this tutorial.

##What are APIs actually?
APIs or Application Programming Interface acts like an intermediate between server and the client that brings or *fetches* information from the server to the client.

With that data, you can create applications like a weather app, which without APIs is practically impossible. 

Why? Because you need to have satellites and huge amount of system to harness the information from satellites, which contain the forecast data.

Now that you know what an API actually is, let's take a quick glance at what we're going to do get data today!

I am not going to focus much on UI today, since it's all about logic for today.

##Our Agenda for today:

1. Get your API key from https://openweathermap.org
2. Make a `XHR request` to the https://openweathermap.org server and get the JSON file.
3. Get the required info from JSON file.
4. Show the data to users.

I recommend you use the console for showing the data, because showing the information in screen isn't agile and effective.

With that said, let's get our hands dirty.

##Making a XHR Request

What on earth is XHR? XHR stands for XML HTTP Request. From the name, you can find out it's a HTTP request for XML. 

Irony that we're using it in Javascript? Nope.

Actually, we're using AJAX method as told before. AJAX stands for Asynchronous JavaScript and XML. Since this method is used in both JS and XML, XHR request becomes relevant to JavaScript too.

The thing that actually is ironical is that we're repeating the word 'Request'.

Till now, you have learnt synchronous JavaScript, which executes step by step or line by line.

But when it comes to APIs, you'll use asynchronous Javascript, which doesn't wait for an action or a function to get over. 

So, this will heavily reduce wait times, which in turn doesn't annoy the user.

Coming back to the request, it is being heavily used in AJAX. You could say that XHR is a huge part of AJAX.

Now, let's create a `function` namely `getweather()`. Pass `e` (preferably) inside the parameters. This will be used to troubleshoot errors.

Now, let's create a constant `xhr` with value `new XMLhttpRequest()`. the `new` keyword is used to create an `object`.

###Deep dive into Objects

An `object` is a data type that's used in OOP (Object Oriented Programming). Consider an `object` like a real life object, which has properties.

For example, `let car =  new object();`. Now, let's define the properties of this object, `car`.

```javascript
car.color = 'red';
car.model = 'Challenger';
car.manufacturer = 'Dodge';

``` 
Seems easy, right? So, I correlated a real life object, which is a Dodge Challenger red car with a JavaScript Object, which has these properties of real life car defined.

There are ton of use cases. Imagine you are creating a user database. There are about a 100 users. So, you can create a `people` object to define the basic properties of your users.

```javascript
function User(name, email, address){

this.name = name;
this.emailid = email;
this.address = address;

}

```
*Notice the use of `this` keyword. The `this` keyword refers to `User` in this function or context. The value of `this` keyword changes with context or the function.*

What I showed you before is creating a simple object, used for generally theoretical purposes.

What I showed you is a constructor function, which helps us assign the properties of `User` to those 3 variables mentioned as parameters.

So, let's create a new user:
```
let Ken  = new User('Ken', 'ken@random.com', 'Times Square, NYC');
```
Now, we've created a new user with name Ken, email 'ken@random.com', and with his address as 'Times Square, NYC'.

Now, we can create as many users as we want with a base `Object` of `User`. 

This forms the crux of `OOP`, which is an important part of probably every programming language.

So, this knowledge is enough to help us call APIs.

##Continuing with XHR
Now, let's use the `open()` method (a function present inside an object).

```javascript
xhr.open('GET', `https://api.openweathermap.org/data/2.5/weather?q=ANYCITYFORNOW&appid=YOURAPIKEY&units=metric`, true);

```
When it comes to APIs, there are a few methods that comes to use.

1. GET
2. PUT
3. POST 
4. DELETE
5. PATCH
6. HEAD

These methods refer to these 5 operations respectively.

1. READ
2. UPDATE
3. WRITE
4. DELETE
5. Partial Modifications
6. Similar to GET, but provides response without body.

We'll be using GET, because we want to just read the data and obtain it from the server.

I used template literals (backticks) for the API key, more on that later.

So, after this, we'll use `xhr.onload()` method. This accepts a callback function or a function that gets executed after `xhr.onload` is done.

The `xhr.onload()` is simple to understand: After the request is done and you get the data, what should be done.

Now in this function there are 2 conditions, for which we will be using `if` and `else` statements.

Take a look at this code:

```javascript
  xhr.onload = function (data){
        if (this.status === 200){
            
            let response = JSON.parse(this.responseText);
            console.log (response);            
        }

        else{
            console.log('Something went wrong.'); 
        }
    }
``` 

the `this.status` is the status code server returns after the request. 200 means the request is OK, so we've used 200 here.

I've passed `data` as the argument here, just in case to troubleshoot errors. 

`responseText` is the text that server provides after our request. We've to convert it into JSON, so that we can get the required data, therefore I used `JSON.parse()` method.

Now, you can console log the `response` variable.

Try running the code, and see if it works. Works? nope.

We didn't send the request yet! use `xhr.send()` after the above code.

Now open the console and check if it works. It should work. If it doesn't check the API link once more and see if you have substituted the right values.

##Getting the required values
Now getting the required values is really simple. Take a look at the JSON and see the all the values closely. 

The `main` JSON contains the current temperature, minimum temperature and maximum temperature.

Let's store the temperature value in `temp` variable.

```javascript
let temp = response.main.temp;
```

Console log it and see if it works. It works!

Store the required values in respective variables and try console logging it. If all works, you have successfully done the API calling right!

Now, take the input element of your webpage, and call it with its `id` or `class` by `document.getElementById` or `document.getElementByClass`.

Use the value property and substitute it in the link. Template literals lets you do this by adding `${value}`. 

So, we have pretty much completed the API calling!