Working with APIs in JavaScript - CodingQue

Working with APIs in JavaScript

APIs (Application Programming Interfaces) allow applications to communicate with each other and exchange data. JavaScript’s fetch function lets us make requests to external APIs and handle the responses, which are often in JSON format. Let’s explore how to use fetch to interact with APIs, with examples.

Understanding the Fetch API

The fetch function is used to request data from a specific URL. This function returns a promise, making it an ideal tool for asynchronous operations. Here’s a basic example of fetching data from an API endpoint:

fetch('https://api.example.com/data')
    .then(response => response.json()) // Parse the JSON data
    .then(data => console.log(data)) // Handle the data
    .catch(error => console.error('Error fetching data:', error));

Using the Fetch API to Get Data

In this example, we’ll use a sample API to retrieve user data. The fetch function first retrieves the response, and .then parses it into JSON format. The data can then be displayed in the console or manipulated further.

fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(users => {
        users.forEach(user => {
            console.log('User:', user.name);
        });
    })
    .catch(error => console.error('Error fetching users:', error));

Example: Displaying Data on the Page

Let’s take it further by displaying the API data directly on the page. This example fetches user data from a placeholder API and dynamically inserts it into a list.

<ul id="userList"></ul>

<script>
fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(users => {
        const userList = document.getElementById('userList');
        users.forEach(user => {
            const listItem = document.createElement('li');
            listItem.textContent = user.name;
            userList.appendChild(listItem);
        });
    })
    .catch(error => console.error('Error:', error));
</script>

Handling Errors with Fetch

Error handling is essential when working with APIs. If a fetch request fails (e.g., the API is down), we can catch and handle the error using .catch. In the following example, we check if the response is OK before proceeding, and log an error if not.

fetch('https://api.example.com/invalid-url')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error('Fetch error:', error.message));

Working with JSON Data

API responses are often in JSON format. JavaScript provides easy methods to parse JSON data, making it easy to work with the data once it's retrieved. The response.json() method transforms the response data into a JavaScript object, which we can manipulate or display as needed.

// Parsing JSON Data Example
fetch('https://jsonplaceholder.typicode.com/posts')
    .then(response => response.json())
    .then(posts => {
        posts.forEach(post => {
            console.log('Post:', post.title);
        });
    });
Previous Next
Modern Footer