How to Fetch Data from an API with JavaScript?

In web development, integrating data from external sources is a common task. Application Programming Interfaces (APIs) play an important function in changing data amongst systems. In this blog, we’ll explore the way to Get information from an API with the use of JavaScript, supplying step-by-step the resource of-step commands with complete code examples of how API Fetch.

What is API?

Before we go into the code, let’s take a second to understand what an API is. An API, which stands for Application Programming Interface, is like a fixed of guidelines and protocols that allow one among a type software program packages to speak to every Different. It’s pretty cool because it allows us to request Data for Data Display from outside servers and seamlessly Web API integration it into Web applications.

Pre-requisites

Before you start, ensure you have got a primary knowledge of HTML, CSS, and JavaScript. First, ensure you have a code editor (in conjunction with Visual Studio Code) and a web browser set up for your tool.  Let’s get started!

Steps To Fetch Data from an API with JavaScript

Here is a simple step-by-step guide to fetch data from an API with JavaScript:

Step 1: Select an API to Fetch

First, decide which API you want to fetch data from. In this tutorial, we will use the JSONPlaceholder Demo API, which is a fake online REST API to test and prototype.

Step 2: Create Your Project

Create a new HTML file and configure the basic settings. Add a script tag to the head section for your JavaScript code.

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>API Data Fetching</title>     <script defer src="app.js"></script> </head> <body> </body> </html>
Code language: HTML, XML (xml)

Step 3:  Fetch API For Fetching Data:

The JavaScript Data Fetch API affords a modern, smooth approach to HTTP requests. Let’s create an easy feature to fetch data from the JSONPlaceholder API.

// app.js function fetchData() {     fetch('https://jsonplaceholder.typicode.com/todos/1')         .then(response => response.json())         .then(data => {             console.log(data);         })         .catch(error => {             console.error('Error:', error);         }); } fetchData();
Code language: JavaScript (javascript)

In this case, we use the ‘fetch’ function to make a GET request for the specified URL. The response is then converted to JSON with the use of the ‘.Json()’ method. Finally, we send the data to the console.

Step 4: Getting Data for Display: 

We now take the Data Display it on our website.

// app.js function fetchData() {     fetch('https://jsonplaceholder.typicode.com/todos/1')         .then(response => response.json())         .then(data => {             displayData(data);         })         .catch(error => {             console.error('Error:', error);         }); } function displayData(data) {     const resultContainer = document.createElement('div');     resultContainer.innerHTML = `<h2>Title: ${data.title}</h2>                                 <p>Completed: ${data.completed}</p>`;     document.body.appendChild(resultContainer); }
Code language: JavaScript (javascript)

fetchData();

In this step, we create a ‘displayData’ function that takes the data taken as parameters and dynamically creates HTML elements to display the information.

Step 5: Handling the User Input:

Let’s enhance our example by requiring users to enter a specific job ID and fetch the corresponding data for User Input API.

// app.js function fetchDataById(id) {     fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)         .then(response => response.json())         .then(data => {             displayData(data);         })         .catch(error => {             console.error('Error:', error);         }); } function displayData(data) {     const resultContainer = document.createElement('div');     resultContainer.innerHTML = `<h2>Title: ${data.title}</h2>                                 <p>Completed: ${data.completed}</p>`;     document.body.appendChild(resultContainer); } const inputId = prompt('Enter task ID:'); fetchDataById(inputId);
Code language: JavaScript (javascript)

Then, users can enter a specific job ID, and the corresponding data will be retrieved and displayed on the web page.

The Final code of app.js is shown below

So this is the final code which looks like this, it is the logic of how to fetch data from an API which is shown below of Fetching with JS;

// app.js // Step 3: Fetching Data with the Fetch API function fetchData() {     fetch('https://jsonplaceholder.typicode.com/todos/1')         .then(response => response.json())         .then(data => {             displayData(data);         })         .catch(error => {             console.error('Error:', error);         }); } // Step 4: Displaying the Data function displayData(data) {     const resultContainer = document.createElement('div');     resultContainer.innerHTML = `<h2>Title: ${data.title}</h2>                                 <p>Completed: ${data.completed}</p>`;     document.body.appendChild(resultContainer); } // Step 5: Handling User Input function fetchDataById(id) {     fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)         .then(response => response.json())         .then(data => {             displayData(data);         })         .catch(error => {             console.error('Error:', error);         }); } const inputId = prompt('Enter task ID:'); fetchDataById(inputId); // Initial fetch (you can comment this line out if using Step 5 with user input)  fetchData();
Code language: JavaScript (javascript)

This is a basic example of fetching data from An API through JavaScript.

Summary

Fetching data from an API the use of JavaScript Data is a key necessity for web developers. The Fetch API simplifies the technique, permitting you to make asynchronous requests and manage responses comfortably. With the know-how received from this path, you can now incorporate outside facts into your internet packages, beginning the door to an extensive style of opportunities to create a greater dynamic and interactive consumer enjoy


Posted

in

by

Recent Post

  • Generative AI for IT: Integration approaches, use cases, challenges, ROI evaluation and future outlook

    Generative AI is a game-changer in the IT sector, driving significant cost reductions and operational efficiencies. According to a BCG analysis, Generative AI (GenAI) has the potential to deliver up to 10% savings on IT spending—a transformation that is reshaping multiple facets of technology. The impact is especially profound in application development, where nearly 75% […]

  • Generative AI in Manufacturing: Integration approaches, use cases and future outlook

    Generative AI is reshaping manufacturing by providing advanced solutions to longstanding challenges in the industry. With its ability to streamline production, optimize resource allocation, and enhance quality control, GenAI offers manufacturers new levels of operational efficiency and innovation. Unlike traditional automation, which primarily focuses on repetitive tasks, GenAI enables more dynamic and data-driven decision-making processes, […]

  • Generative AI in Healthcare: Integration, use cases, challenges, ROI, and future outlook

    Generative AI (GenAI) is revolutionizing the healthcare industry, enabling enhanced patient care, operational efficiency, and advanced decision-making. From automating administrative workflows to assisting in clinical diagnoses, GenAI is reshaping how healthcare providers, payers, and technology firms deliver services. A Q1 2024 survey of 100 US healthcare leaders revealed that over 70% have already implemented or […]

  • Generative AI in Hospitality: Integration, Use Cases, Challenges, and Future Outlook

    Generative AI is revolutionizing the hospitality industry, redefining guest experiences, and streamlining operations with intelligent automation. According to market research, the generative AI market in the hospitality sector was valued at USD 16.3 billion in 2023 and is projected to skyrocket to USD 439 billion by 2033, reflecting an impressive CAGR of 40.2% from 2024 […]

  • Generative AI for Contract Management: Overview, Use Cases, Implementation Strategies, and Future Trends

    Effective contract management is a cornerstone of business success, ensuring compliance, operational efficiency, and seamless negotiations. Yet, managing complex agreements across departments often proves daunting, particularly for large organizations. The TalkTo Application, a generative AI-powered platform, redefines contract management by automating and optimizing critical processes, enabling businesses to reduce operational friction and improve financial outcomes. […]

  • Generative AI in customer service: Integration approaches, use cases, best practices, and future outlook

    Introduction The rise of generative AI is revolutionizing customer service, heralding a new era of intelligent, responsive, and personalized customer interactions. As businesses strive to meet evolving customer expectations, these advanced technologies are becoming indispensable for creating dynamic and meaningful engagement. But what does this shift mean for the future of customer relationships? Generative AI […]

Click to Copy