JavaScript Web APIs

An API, or Application Programming Interface, is a way for different software components to communicate with each other. In the context of web development, a Web API allows your browser or web app to interact with external resources or services, such as databases, servers, or even third-party services like Google Maps or Twitter. Think of it as a bridge that allows your web application to request data or services from another system and use it within your site.

APIs can be native (built into the browser) or third-party (provided by external services or companies). Native APIs give you access to the browser's built-in capabilities, like manipulating the DOM or making network requests, while third-party APIs allow you to use external data or services, such as weather data or payment gateways.

In this chapter, we will cover both native JavaScript Web APIs and a few popular third-party APIs. This will give you a solid foundation for working with APIs to build powerful web applications.

Native Web APIs

Native Web APIs are built directly into the browser, allowing your JavaScript code to interact with the web page, the browser, and even the underlying system in various ways. We’ll start by exploring a few of the most commonly used native APIs.

DOM Manipulation API

The DOM (Document Object Model) API allows you to interact with and manipulate the structure of an HTML document. Every web page is represented as a tree of nodes (elements like <div>, <p>, etc.), and with JavaScript, you can modify these nodes to create dynamic, interactive content.

Why is it important? Manipulating the DOM allows you to:

  • Dynamically update the content of your web page.
  • Add or remove HTML elements.
  • Change the appearance of elements (e.g., styles or attributes).
  • Attach events like clicks or key presses to elements.

Example - Changing an element's text:

<!DOCTYPE html>
<html>
  <body>
    <h1 id="header">Welcome to the page!</h1>
    <button onclick="changeText()">Change Text</button>

    <script>
      function changeText() {
        document.getElementById("header").innerHTML = "Hello, JavaScript!";
      }
    </script>
  </body>
</html>

In this example, we use the getElementById method to find an HTML element by its id and then change its content when the button is clicked. This is just one simple example of how powerful the DOM API is.

Key Methods:

  • document.getElementById(): Finds an element by its ID.
  • document.querySelector(): Finds an element by its CSS selector.
  • element.innerHTML: Changes the inner content of an element.
  • element.style: Changes the CSS style of an element.

Fetch API

The Fetch API provides a modern, powerful, and flexible approach to making HTTP requests in JavaScript. It's a significant improvement over the older XMLHttpRequest and is now the preferred method for making network requests in web applications.

17.3.1. What is the Fetch API?

The Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers. It returns promises and works with async/await syntax, making it easier to work with than older technologies like XMLHttpRequest.

17.3.1.1. Basic Fetch GET Request

Making a GET Request

The simplest use of the Fetch API is to retrieve data from a server. The basic syntax is fetch(url).

Example: Fetching JSON Data

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

In this example, a JavaScript fetch request is made to 'https://jsonplaceholder.typicode.com/posts/1', which, on success, converts the response to JSON and logs it to the console, and on failure, logs the error.

17.3.1.2. Handling Responses

Not all responses from fetch are successful. The Fetch API considers a request a success if it receives a response, including a response that indicates an HTTP error like 404 or 500.

Checking Response Status

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

In this example, the response check: if (!response.ok) checks if the response status is not successful. The throw new Error creates a new error that will be caught by .catch. If the response is ok, it processes the data as before.

17.3.1.3. Sending Data with POST Requests

The Fetch API can also be used to send data to a server.

Example: Sending JSON Data

const postData = {
  title: 'My New Post',
  body: 'This is the post body.',
  userId: 1
};

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(postData)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

In this example, the method and headers properties in the second argument configure the request type and headers. The body property contains the data to be sent, converted to a JSON string, while the response processes the response like in previous examples.

17.3.2. PATCH, PUT, and DELETE Methods

After learning how to send data with POST requests, it’s important to understand how to update or delete data using the Fetch API. We can use the PATCH, PUT, and DELETE methods to accomplish these tasks.

17.3.2.1. Updating Data with PUT Requests

The PUT method is used to update an entire resource. When you use PUT, the entire entity is replaced with the new data you send. This means that even if you're only updating a part of a resource, you must send the complete object, including the fields that haven’t changed.

Example: Updating Data with PUT

const putData = {
    title: 'Updated Post Title',
    body: 'Updated post body content.',
    userId: 1
};

fetch('https://jsonplaceholder.typicode.com/posts/1', {
    method: 'PUT',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(putData)
}).then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

In this example, we update an existing post (with ID 1) by sending the entire object. If you leave out any fields from the object, they will be replaced with default or empty values.

17.3.2.2. Partially Updating Data with PATCH Requests

The PATCH method allows you to partially update a resource. Unlike PUT, you can only include the fields you want to modify, leaving the rest of the resource unchanged.

Example: Updating Only the Title with PATCH

const patchData = {
    title: 'Partially Updated Title'
};

fetch('https://jsonplaceholder.typicode.com/posts/1', {
    method: 'PATCH',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(patchData)
}).then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

In this case, we are updating only the title of the post with ID 1. The rest of the post remains unchanged. PATCH is useful when you want to update a specific field without affecting the other properties of the resource.

17.3.2.3. Deleting Data with DELETE Requests

The DELETE method is used to remove a resource from the server. This is a straightforward process, as you don’t need to send any data—just the correct endpoint.

Example: Deleting a Resource

fetch('https://jsonplaceholder.typicode.com/posts/1', {
    method: 'DELETE'
})
.then(response => {
    if (response.ok) {
        console.log('Resource deleted successfully');
    } else {
        console.error('Failed to delete the resource');
    }
})
.catch(error => console.error('Error:', error));

In this example, we send a DELETE request to remove the post with ID 1. If the request is successful, we log a confirmation message; otherwise, we log an error.

Summary

  • PUT: Use PUT to completely replace an existing resource with new data.
  • PATCH: Use PATCH to partially update a resource, modifying only the specified fields.
  • DELETE: Use DELETE to remove a resource from the server.

Each of these methods expands on the functionality of the Fetch API, allowing you to interact more comprehensively with the server by updating and removing data, in addition to simply fetching it or creating new records.

17.3.3. Advanced Features

Adding Headers

You can add custom headers to your requests. Headers can include authentication tokens, specify content types, and more.

fetch('https://api.example.com/data', {
  headers: {
    'Authorization': 'Bearer your-token-here',
    'Content-Type': 'application/json'
  }
})

Error Handling Improvements

Handling network errors and HTTP errors separately can provide better error handling.

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('HTTP status ' + response.status);
    }
    return response.json();
  })
  .catch(error => {
    if (error.name === 'TypeError') {
      console.error('Network error or CORS issue:', error);
    } else {
      console.error('HTTP error:', error);
    }
  });

The Fetch API is a versatile tool for making HTTP requests in JavaScript. It handles a wide range of use cases, from simple data retrieval to complex requests with custom headers and error handling. By understanding how to use the Fetch API, you can effectively communicate with servers in your web applications.

Web Storage APIs

The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.

In modern web applications, storing data on the client-side is a common task. JavaScript provides two main methods for storing data in the browser: Local Storage and Session Storage. Both of these storage mechanisms allow you to store key-value pairs directly in the user's browser, but they differ in how long the data persists.

17.4.1. Understanding Local Storage and Session Storage

Both Local Storage and Session Storage are part of the Web Storage API. They offer a simple and convenient way to store small amounts of data (up to 5MB) that can be accessed later without requiring a server.

  • Local Storage: Data is stored persistently in the browser. It remains available even after the browser is closed and reopened.
  • Session Storage: Data is stored temporarily for the duration of a single session. It is cleared when the page session ends, such as when the browser tab is closed.

17.4.1.1. Local Storage

Local Storage stores data with no expiration time. The data will persist even after the browser or tab is closed and will be available when the user returns to the site.

Setting Data in Local Storage

localStorage.setItem('key', 'value');

Example: Storing a user’s name in Local Storage

localStorage.setItem('username', 'John Doe');

In this example, the setItem method stores the value 'John Doe' with the key 'username'. This value will remain available across page reloads or even if the browser is closed and reopened.

Retrieving Data from Local Storage

To retrieve the stored value, use the getItem method:

let username = localStorage.getItem('username');
console.log(username); // Output: John Doe

If the data exists, the value associated with the key will be returned. If the key does not exist, it will return null.

Removing Data from Local Storage

You can also remove specific items from Local Storage:

localStorage.removeItem('username');

This will remove the username key and its associated value from Local Storage.

Clearing All Data from Local Storage

To clear all data stored in Local Storage, use the clear method:

localStorage.clear();

This will remove all key-value pairs stored in Local Storage for the current domain.

17.4.1.2. Session Storage

Session Storage works similarly to Local Storage, but the data is only available for the duration of the page session. Once the browser tab is closed, the stored data is lost.

Setting Data in Session Storage

sessionStorage.setItem('sessionKey', 'sessionValue');

Example: Storing a session ID in Session Storage

sessionStorage.setItem('sessionId', '123456');

This data will be available as long as the browser tab remains open.

Retrieving Data from Session Storage

To retrieve the stored value, use the getItem method:

let sessionId = sessionStorage.getItem('sessionId');
console.log(sessionId); // Output: 123456

Like Local Storage, this will return the value associated with the key or null if the key doesn’t exist.

Removing Data from Session Storage

You can remove specific items from Session Storage using the removeItem method:

sessionStorage.removeItem('sessionId');

Clearing All Data from Session Storage

To clear all the data from Session Storage for the current tab, use the clear method:

sessionStorage.clear();

This will remove all session-based key-value pairs for that tab.

17.4.2. Differences Between Local Storage and Session Storage

  • Persistence: Data in Local Storage persists even after the browser is closed, while Session Storage data is cleared when the tab is closed.
  • Scope: Both storage types are scoped to the domain, but Session Storage is also scoped to individual tabs. Different tabs opened to the same site will have separate Session Storage data.
  • Storage Limits: Both typically have the same storage limit of 5MB, but this can vary slightly between browsers.

Example Use Cases

Local Storage: Suitable for storing data that should persist between visits, such as user preferences, themes, or tokens for authentication.


Example: Saving user theme preferences.

localStorage.setItem('theme', 'dark');
let userTheme = localStorage.getItem('theme');

Session Storage: Ideal for data that is only needed temporarily within a session, such as a user’s progress through a multi-step form.

Example: Storing form progress across pages.

sessionStorage.setItem('step', '2');
let currentStep = sessionStorage.getItem('step');

Summary

  • Local Storage is used for long-term storage of key-value pairs, where data persists across sessions.
  • Session Storage is used for temporary storage that lasts only during the user's session on that page.

By utilizing both Local and Session Storage effectively, you can enhance the user experience by storing data on the client side, reducing the need for constant server requests.

Geolocation API

The Geolocation API allows you to access the geographical location of the user. It provides latitude and longitude coordinates, which can be useful for mapping, location-based services, or personalized content based on the user’s location.

Why is it important?

  • It enables location-based functionality, like showing the user's current position on a map or providing nearby recommendations.

Key Methods:

  • navigator.geolocation.getCurrentPosition(successCallback, errorCallback): Retrieves the user’s current location.

Example - Getting the user's location:

<!DOCTYPE html>
<html>
  <body>
    <button onclick="getLocation()">Get Location</button>
    <p id="output"></p>


    <script>
      function getLocation() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(showPosition, showError);
        } else {
          document.getElementById("output").innerHTML = "Geolocation is not supported by this browser.";
        }
      }

      function showPosition(position) {
        document.getElementById("output").innerHTML = "Latitude: " + position.coords.latitude +
          "<br>Longitude: " + position.coords.longitude;
      }

      function showError(error) {
        document.getElementById("output").innerHTML = "Unable to retrieve your location.";
      }
    </script>
  </body>
</html>

This code gets the user’s location and displays their latitude and longitude.

Canvas API

The Canvas API allows you to draw graphics, animations, and even create interactive games in the browser using JavaScript. It’s a powerful tool for adding custom visual elements to your web pages.

Why is it important?

  • It’s perfect for creating dynamic, interactive content such as charts, games, or animations.

Key Methods:

  • canvas.getContext('2d'): Provides a 2D drawing context for the canvas element.
  • context.fillRect(x, y, width, height): Draws a filled rectangle on the canvas.

Example - Drawing on a canvas:

<!DOCTYPE html>
<html>
  <body>
    <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000;"></canvas>
    <script>
      var canvas = document.getElementById("myCanvas");
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "#FF0000";
      ctx.fillRect(20, 20, 150, 100);
    </script>
  </body>
</html>

Native Web APIs open up a world of possibilities for your web applications, from manipulating content dynamically to working with hardware features like location services and cameras. By mastering these APIs, you can create more responsive, feature-rich applications that provide a better user experience. Next, we’ll explore third-party APIs, which allow you to extend your app’s functionality with external services.

Third-Party APIs

Third-party APIs allow you to integrate external services into your web application, such as maps, social media, or weather data. These services expose their own APIs, often through HTTP, allowing you to fetch data and display it on your website.

17.7.1. Google Maps API

The Google Maps API allows you to embed interactive maps into your web application and customize them with markers, routes, and other map features.

Why is it important?

  • It helps you provide location-based services in your web app.

  • You can display detailed maps, driving directions, or places of interest.

Example - Embedding a simple map:

<html>
  <body>
    <h3>My Location</h3>
    <div id="map" style="width:400px;height:400px;"></div>


    <script>
      function initMap() {
        var location = {lat: -25.363, lng: 131.044};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: location
        });
        var marker = new google.maps.Marker({position: location, map: map});
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>

 

In this example, a Google map is embedded on the page and centered on a specific location. You need an API key from Google to use this service.

How to Get a Google Maps API Key:

  1. Go to Google Cloud Console:
    • Visit Google Cloud Console.
    • Sign in with your Google account (if you don’t have one, you’ll need to create one).
  2. Create a New Project:
    • Click the project dropdown at the top of the page and select New Project.
    • Give your project a name (e.g., "My Maps App") and click Create.
  3. Enable Google Maps API:
    • In the left-hand menu, click on APIs & Services > Library.
    • Search for "Google Maps JavaScript API" and click on it.
    • Click Enable to enable the API for your project.
  4. Get an API Key:
    • After enabling the API, go to APIs & Services > Credentials.
    • Click on Create Credentials and select API Key.
    • Google will generate an API key for you. Copy this key.
  5. Restrict Your API Key (Recommended):
    • To prevent misuse, it's a good idea to restrict your API key to specific domains or IP addresses.
    • In the Credentials page, click on your API key and add restrictions (e.g., only allow the API to be used from your website's domain).
  6. Insert Your API Key into Your Code:
    • Replace the placeholder YOUR_API_KEY in the script tag with your actual API key.

17.7.2. OpenWeather API

The OpenWeather API allows you to retrieve weather data for any city in the world.

Why is it important?

  • Provides current weather, forecasts, and historical weather data.
  • Useful for building weather apps or adding weather features to an existing application.

Example - Fetching weather data:

<html>
  <body>
    <h2>Weather in London</h2>
    <button onclick="getWeather()">Get Weather</button>
    <pre id="weatherOutput"></pre>


    <script>
      function getWeather() {
        fetch('https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY')
          .then(response => response.json())
          .then(data => {
            document.getElementById("weatherOutput").innerHTML = JSON.stringify(data, null, 2);
          });
      }
    </script>
  </body>
</html>

This example fetches weather data for London using the OpenWeather API and displays the result. You will need an API key to use this service.

How to Get an OpenWeather API Key:

  1. Sign Up for an OpenWeather Account:
    • Go to OpenWeather’s website and create a free account.
  2. Create a New API Key:
    • Once logged in, go to the API keys section in your account dashboard.
    • Click Create Key, name your API key (e.g., "Weather App Key"), and click Generate.
    • Your new API key will appear on the screen. Copy this key.
  3. Use the API Key in Your Code:
    • Replace YOUR_API_KEY in the example above with the API key you just generated.
  4. Choose the Right Subscription Plan:
    • OpenWeather provides a free tier with limited requests per minute, which is great for personal projects and small applications.
    • If you need more requests or advanced features, you may need to upgrade to a paid plan.

Web APIs are powerful tools that extend the capabilities of your web applications. Whether you're using native APIs like the DOM and Fetch to manipulate the web page or integrating third-party services like Google Maps and OpenWeather, APIs provide endless possibilities for building interactive and dynamic web applications. Keep exploring and practicing, and soon you'll be building web apps that are rich in features and functionality!

Updated on:

Part of our complete: JavaScript Fundamentals guide

Want exercises and real projects for this lesson? Get the full course.