How to Use an API with HTML

Overview

Using a restaurant scenario, the menu acts as the API. It provides a list of options (here we have foods) to choose from. When you've placed your order, the waiter acts as the middleman who takes your order (the API request), to the kitchen (the server). The kitchen cooks your food (API Response) and sends it to your table (your application).

What is an API

API means Application Programming Interface. It is a communication link between two different applications. API sends and receives data (information) between two applications. APIs help you to use the features of an application or website for your web projects rather than building from scratch. As regards this tutorial, we'll focus on getting an API from the target source and integrating it into HTML.

Understanding HTTP Requests and Responses

HTTP is Hypertext Transfer Protocol. HTTP is in charge of data exchange on the world wide web. The protocol involves sending an HTTP request by the web browser and fetching the required information called the HTTP response by the web server. This response is usually in a form called JSON (JavaScript Object Notation). For a better understanding, when you type in a URL in your browser or anything, the URL is regarded as an HTTP request. The HTTP then searches the world wide web to give you an appropriate response called HTTP response.

However, in this guide, an API request will be made using JavaScript and then update our HTML page using the retrieved data.

Choosing an API

Your choice of API should be based on the data or functionality you need. They are different types of APIs you can use for your web projects, such as:

  • Google Maps API

  • Twitter API

  • Facebook API

  • OpenWeatherMap API

  • GitHub API

There is a need to read the API's documentation and research the community support behind the API, as well as any cost involved in using the API. However, in this tutorial, we'll use OpenWeatherMap API.

Registering for the API

To get the API of OpenWeatherMap, you have to sign up on their website. Create an account on the OpenWeatherMap website by signing up. Complete the registration and verification process by verifying your email. You can repeat the same or similar registration process for other API's.

Getting an API key

Following the successful account registration, proceed to get your API key by navigating to the API section on the OpenWeatherMap website. The API key serves as a password. An API key is a unique identifier that allows you to access the API's data and functionality.

To obtain an API key you need to follow the instructions on the API document.

Understanding the API Documentation

You will need to understand the API documentation before using the API with HTML. The API documentation provides information on the endpoints, parameters, and response formats for the API. Endpoints are specific URLs that provide access to the API's data or functionality. Parameters are values passed to an endpoint to customize the response data. Response formats indicate how the API will format the response data.

For better understanding, read the API's overview documentation, which will provide a high-level description of the API's functionality. From there, you can dive into the specific documentation for each endpoint you want to use.

Create an HTML file

To display the weather data you have to create an HTML file and add a div with an id. It will help to display the weather data. Code sample:

<!DOCTYPE html>
<html>
  <head>
    <title>Using an API with HTML</title>
  </head>
  <body>
    <h1>Weather App</h1>
    <div id="weather"></div>
    <script src="app.js"></script>
  </body>
</html>

Create a JavaScript file

Create a JavaScript file and name it app.js. This file will contain the code that retrieves the weather data from the OpenWeatherMap API and updates the HTML page with the retrieved data.

Make an API request

We'll proceed to make an API request. Code sample:

function getWeather() {
  fetch(`https://api.openweathermap.org/data/2.5/weather?q=New York&appid=YOUR_API_KEY&units=metric`)
    .then(response => response.json())
    .then(data => {
      console.log(data);
    })
    .catch(error => console.error(error));
}

get weather();

The JavaScript code uses the "fetch function" to make an API request to the OpenWeatherMap API. It retrieves weather data for New York and then logs the data to the console. Replace YOUR_API_KEY with your actual API key.

Update the HTML page

Now that we have the weather data, we can update the HTML page with the retrieved data. In the app.js file, select the div element that we created earlier and update its innerHTML property with the weather data. For example, you can use the following code:

function getWeather() {
  fetch(`https://api.openweathermap.org/data/2.5/weather?q=New York&appid=YOUR_API_KEY&units=metric`)
    .then(response => response.json())
    .then(data => {
      const weatherDiv = document.querySelector('#weather');
      weatherDiv.innerHTML = `
        <p>Temperature: ${data.main.temp}°C</p>
        <p>Description: ${data.weather[0].description}</p>
        <p>Wind Speed: ${data.wind.speed} m/s</p>
      `;
    })
    .catch(error => console.error(error));
}

getWeather();
In this code, we are selecting the div element with the id of "weather" and updating its innerHTML property with the temperature, description, and wind speed data retrieved from the API.

Step 7: Test the code
Save the HTML and JavaScript files and open the HTML file

In this code, we are selecting the div element with the id of "weather" and updating its innerHTML property with the temperature, description, and wind speed data retrieved from the API.

Test the code

Save the HTML and JavaScript files and open the HTML file.

Conclusion

I'd like to say big congrats for successfully integrating an API into HTML. Choosing the right API can help you create a wonderful web application with amazing features and user friendly.

The key basics to using an API with HTML is to choose the API that best suit your project and obtain the API key. Moreover, you need to understand the API's documentation, including the endpoints, parameters, and response formats. Once you have this information, you can make API requests using JavaScript and retrieve the data you need for your HTML pages.

I hope this tutorial found you well and will help to increase your skillsets and get your projects accomplished.

Thanks for reading!

0
Subscribe to my newsletter

Read articles from Kelechukwu Awoke directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kelechukwu Awoke
Kelechukwu Awoke

I am a Front End Developer. Technical writer. Tech enthusiast. Always optimistic!