Making API requests

Build web apps with NodeJS & Express

🕑 This lesson will take about 30 minutes

In this lesson, you will learn how to make requests to an API. There are many free APIs that you can use for different services and they all mostly follow a very similar method for making requests and handling responses, however, we will use the OpenWeatherMap API as an example for this tutorial.

The OpenWeatherMap API allows us to fetch weather data for a location in a request and use that data in our own web apps. We will use the API to display temperature and humidity for a particular city but there is much more data you can get from this API. To get started, we will just display weather data for one city in the console to test that our application can make requests and receive responses. Over the next lessons, we will create a form so the user can enter a city/suburb name in a text input box and get the weather data for a custom location.

Get your API key

To get started, go to https://openweathermap.org/api . Scroll down and click "Subscribe" under the heading “Current Weather Data”. Scroll down on the next page and click on “Get API key” in the “Free” plan column. You will need to sign up for a free account to get your API key. Alternatively, if you are already signed in, click on your account name in the top right corner of the screen and then click on My API keys to generate a new key. You will need to use this key in your app's code later.

Step 1 - Create a new NodeJS/Express app project

Now, create a fresh NodeJS/Express app. To do this, create a new folder/directory on your computer (we will call it “weatherapp” in this tutorial) and setup your app in this folder (follow the instructions from the first lesson in this course if you need help setting up the app).

After running the npm init -y command (to set up your new project) and npm i express command (to install Express) in your terminal, you will also need to install the following packages for this project. Run each of these commands in your terminal to install each of the following packages

  • ejs (run the command npm i ejs in your terminal)

  • request (run the command npm i request in your terminal)

  • body-parser (run the command npm i body-parser in your terminal)

Note: If you’re using Replit.com to write your code, then you won’t need to use a terminal to run commands to install packages. You can search for and install packages from the Packages tab, otherwise, Replit may just automatically install them when you run the app for the first time.

You will need to use two new packages in this tutorial: request (used for making requests to an API), and body-parser (used for parsing or reading the data that comes back from an API request).

Step 2 - Add the server code (index.js file)

In your project’s directory/folder, create a new file called index.js and add the following code. Make sure you replace the value in the apiKey variable with your actual API key that you obtained from OpenWeatherMap:

Let's break down the different parts of this code.

  • When the app.get(‘/’) function is called (when the user requests the home page), the request() function is then called to make a request to the OpenWeatherMap API using the URL (link) provided, get a response, and then store the data from the response in body or return an error message (err) if something doesn't work.

    • The URL for the API request contains both the city/suburb name and the API key

  • After the request to the API is made, it checks if there were any errors making the request, or if the response doesn't provide any useful data (eg. if the city doesn't exist), or if there were no errors and there was some actual weather data that we can use.

  • If weather data is retrieved, it is stored in the weather variable as a string in JSON format.

  • The different parts of the weather data (eg. temperature, humidity) are then extracted from the JSON string by referring to each of the specific pieces of data we want (eg. weather.main.humidity). This data is then logged to the console (it is not displayed on the page yet).

Below we see the URL used to make the request.

Screenshot of URL in code showing the location and apiKey variables in the request URL

If you copy and paste the URL (replacing ‘+location+’ with an actual city/suburb name and ‘+apiKey; with your actual API key) in the address bar of your browser, then you can view all the data that is retrieved.

For example: https://api.openweathermap.org/data/2.5/weather?q=Sydney&units=metric&appid=your_API_key_goes_here

In a JSON data string, we can extract different values by referring to their keys eg. weather.main.temp will extract the current temperature from the response data.

Tip: Go to https://jsonviewer.stack.hu and copy and paste the JSON response data in the Text tab. Then click on the Viewer tab and you can view the JSON data as a tree, making it easier to find the different pieces of data in the response.

Step 3 - Create the index.ejs template file

The next step is to create a new directory/folder in your project directory called views and inside the views directory, create a new file called index.ejs . This will be our EJS template for the home page. This file does not need to contain any code at the moment because we won't be displaying the weather information on a web page just yet (we will just log to the console for now). We will add the code for the home page later.

Test your code

  1. Open a new terminal and run the command node index.js to start the server (don’t forget to run the command to navigate to the project directory first if you’re not using VS Code's terminal eg. cd/Desktop/weatherapp). You should see the message “Server started” in the terminal.

  2. Open a new tab in your web browser and navigate to http://localhost:3000 (remember, if you’re using Replit.com, just click the Run button). You won’t see any content on the web page (because we haven’t added any code to the index.ejs template file yet) but if you go back to your terminal, you should see the console logs with the current temperature and humidity data.

In the next lesson, we will look at how to grab more data from the JSON string and then we will build a full weather app with a page to display the weather information. We will also look at how to create a form to get the user’s location for custom weather data.

Next lesson: Working with JSON data