Learning how to use API's

Building a weather forecast application

What is an API?

This article aims to help you understand what an API is, and how to implement one in 4 simple steps!

An Application Programming Interface (API), is essentially a means of communication between computers/computer programs. In this example, the API we are using today, pulls data from OpenWeatherMap's service, so that we can display it in our application.

Step 1: Sign up for an account at home.openweathermap.org/users/sign_up

By signing up for Openweathermap, you'll be able to use their "Current weather and forecast" service, which is what we'll be using to retrieve our data.

Step 2: Retrieve your API Key

Once you've created an account, navigate over to the "My API keys" section and copy your API Key.


Step 3: Create your API object in Javascript

The "key" field should be your API key and the "base" field is where we're retrieving out data from, so that shouldn't differ from the one below.

const api = {
        key: "4d34rqw390eirw0i23094d32qwe",
        base: "https://api.openweathermap.org/data/2.5/"

Step 4: Retrieve weather data

For this example, we've used a user input as a function argument, however you could use a form input or any other textbox value. We then use the fetch() method from the Fetch API (developer.mozilla.org/en-US/docs/Web/API/Fe..), which will retrieve the data we want. This method will read our base field in the "api" object we created earlier. It will then check the weather at the user's prompted location, which is what "weather?q${location}" does. the data provided is automatically set to degrees kelvin, so we use "&units=metric" to convert it. We then pass on out API key as the last part of the argument, so that Openweathermap's service knows we are authorized to use its data.

location = window.prompt("Enter location: ")
function getWeather(location){
            .then(weather => {
            return weather.json();

function printWeather(weather){

We then convert the data sent back, (weather) into JSON, and use the printWeather function to print it out. Going into your dev-tools, you should be able to see the retrieved data!


And that's it!

That's all there is to it, you've successfully pulled data and are displaying it in your browser. Of course, you might want to make it look more visually appealing.

Check out this tutorial by Tyler Potts on how to do so!