Lesson Monday

Note: All examples of API calls in this week’s lessons use just one js file. Business logic and UI logic are mixed together to provide a clear, simple example. However, you are still expected to keep business and UI logic separate in your own applications. You’ll often find code samples online that work in isolation but take some tinkering to incorporate into your own code. It’s important to refactor any code you use so that it properly fits in your application. In this case, that means using a gulpfile, separating concerns and potentially refactoring to use classes and/or constructors and prototypes. If you would like to see an example of how to properly separate your files, check out this tutorial created by Epicodus graduate Jared Eiseman (CSS/Design Oct. 2017).

In the next two lessons, we’ll look at two different ways to make API calls, one using JavaScript, the other with jQuery. Both approaches involve making the API calls asynchronously, so we’ll need to use callbacks to handle the response from the API.

Let's create a page that uses the Open Weather Map API to find and display the current humidity and temperature in a city of the user's choice. We’ll start by using jQuery’s ajax() method to make the API call and return the data. We’ll put all data in the user interface file for now; while this isn’t a good long term solution for separating our user interface and business logic, it will make the code easier to explain.

The front end of our application is simple; a user should be able to input a city, click a button, and then get the current humidity and temperature. Our project directory will have only two files: weather.html and weather-interface.js.

Here’s the code for our user interface file:

weather-interface.js
$(document).ready(function() {
  $('#weatherLocation').click(function() {
    let city = $('#location').val();
    $('#location').val("");
    $.ajax({
      url: `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=[API-KEY-GOES-HERE]`,
      type: 'GET',
      data: {
        format: 'json'
      },
      success: function(response) {
        $('.showHumidity').text(`The humidity in ${city} is ${response.main.humidity}%`);
        $('.showTemp').text(`The temperature in Kelvins is ${response.main.temp}.`);
      },
      error: function() {
        $('#errors').text("There was an error processing your request. Please try again.")
      }
    });
  });
});

Let’s jump directly to the ajax() method. This method is used when we want to make an asynchronous HTTP request. An API call is a HTTP request and we definitely want it to be asynchronous; otherwise the application would freeze up while the user is waiting for a response!

An ajax() call looks like this:

$.ajax({options})

The ajax() method takes a set of key-value pairs as its parameter. In the above example, we use the options (keys) url, type, data, success and error. You can take a look at other options by checking the documentation; one common option that many APIs require is the headers option, which we don’t include in this call.

We start by passing a URL, which uses a template literal to pass in a city variable. (You should get your own API key from OpenWeather; for now, go ahead and put the key directly into the API call. In an upcoming lesson, we’ll see how we can make the key private and store it inside a .env file.)

Then we specify the HTTP method type of the API call. The most common is GET (which means we’re just retrieving information from the API). There are also a number of other HTTP methods as well, including POST.

Next, we add an option for the data type we’ll be retrieving from the API. JSON is the most common format, but you may also see formats such as XML, JSONP, and even YAML.

Our next two options provide callbacks, one for a successful HTTP request, the other for a request that returns an error. Let’s take a closer look at the success callback:

success: function(response) {
  $('.showHumidity').text(`The humidity in ${city} is ${response.main.humidity}%`);
   $('.showTemp').text(`The temperature in Kelvins is ${response.main.temp}.`);
}

When our HTTP request is successful, the response will be passed in as an argument to this function. (We could call the parameter something other than response, but it’s a clear, concise name for it.) We then use jQuery to display the humidity and temperature in HTML classes; we’ll create the HTML soon. There’s one other thing to note: we get the temperature and humidity from response.main. This is because the data for temperature and humidity is nested inside a JSON object like this:

{
  ...
  "main": {
        "temp": 297.15,
        "pressure": 1010,
        "humidity": 94,
        "temp_min": 297.15,
        "temp_max": 297.15
    },
...
}

We target temp by first accessing our response, then main, and then temp. This will become clearer when we start using tools like Postman to see exactly what the JSON response from an API looks like.

The error option is a callback for any errors. We just pass in a simple message; we could also target any error message from the API and return that to the user as well. Regardless, adding the error option is just as important as success. We can’t assume that everything will work in our application and users will assume the application is simply broken if we get an error but don’t return a notification of some kind.

Let’s add the HTML.

weather.html
<html>
  <head>
    <script src="http://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script type="text/javascript" src="weather-interface.js"></script>
    <title>Weather</title>
  </head>
  <body>
    <div class="container">
      <h1>Get Weather Conditions From Anywhere!</h1>
      <label for="location">Enter a location:</label>
      <input id="location" type="text">
      <button class="btn-success" id="weatherLocation">Get Current Humidity!</button>
      <div class="errors"></div>
      <div class="showHumidity"></div>
      <div class="showTemp"></div>
    </div>
  </body>
</html>

If we open weather.html in the browser, we can enter a location (such as portland, oregon) and get the current humidity and temperature (in Kelvins).

Now that we’ve learned how to use jQuery’s ajax() function to make API calls, it’s time to take a look at another way we can make API calls with JavaScript’s XMLHttpRequest object.