How To Use JavaScript Fetch API To Get Data?
Last Updated :
17 Jun, 2025
The Fetch API is a modern way to make HTTP requests in JavaScript. It is built into most browsers and allows developers to make network requests (like getting data from a server) in a simple and efficient way. The Fetch API replaces older techniques like XMLHttpRequest and jQuery's AJAX methods.
Syntax
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error)
In the above syntax:
- url: The URL you want to fetch data from.
- .then(): Handles the response when the request is successful.
- .catch(): Catches any errors if the request fails.
How Fetch Works
The fetch() function is a modern way to make HTTP requests in JavaScript using promises. Here's how it works:
- fetch(url) sends a request to the given URL (default is GET).
- Returns a Promise that resolves to a Response object.
- Use .then() to process the response (e.g., response.json()).
- Use .catch() to handle network errors.
- Does not throw errors for HTTP status codes like 404 — check response.ok manually.
Now let's understand this with the help of example:
JavaScript
fetch('https://fakestoreapi.com/products/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Fetching data from an API- The fetch() function sends a request to the API and retrieves the data for product 1 from the URL provided.
- The response is parsed into JSON with .then(response => response.json()), and the resulting data is logged to the console, while any errors are caught and displayed with .catch().
Handling HTTP Response Status
Handling HTTP response status in the Fetch API helps you manage different outcomes based on the server's response, such as success or error codes. You can check the status to determine what action to take.
JavaScript
fetch('https://fakestoreapi.com/products/1')
.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('Error:', error));
Handling HTTP Response Status- ReadableStream: A stream of data from the server that can be read in chunks.
- locked: false: The stream is not locked and can be read multiple times.
- state: 'readable': The stream is open, and data can be read.
- supportsBYOB: true: You can use your own buffer to receive data.
- bodyUsed: false: The response body has not been read yet.
- ok: true: The request was successful (status code 200-299).
- redirected: false: The request was not redirected.
- type: 'basic': The response is from the same origin.
- url: 'https://fakestoreapi.com/products/1': The URL used for the request.
Using async/await with Fetch API
Using async/await with the Fetch API allows handling asynchronous code in a more readable way. Here's a simple example to fetch data.
JavaScript
async function fetchData() {
try {
const response = await fetch('https://fakestoreapi.com/products/1');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
Using async/await with Fetch API- async function: The `fetchData` function is marked as `async`, which allows the use of `await` within it. This makes the asynchronous code look more like synchronous code, improving readability.
- await fetch(): The `await` keyword pauses the function execution until the `fetch()` request is completed and the response is received. This avoids the need for multiple `.then()` methods and makes the code easier to follow.
- await response.json(): Once the response is received, `await` is used to parse the response body into JSON format. This also ensures that the code waits for the JSON parsing to complete before moving forward.
- Error Handling: Using `try/catch` ensures that any errors during the fetch request or while parsing the response are caught and handled gracefully, preventing the app from crashing.
Handling Errors
Error handling in the Fetch API ensures that issues like network failures or invalid responses are properly managed. Here's a simple example to demonstrate how to handle errors with Fetch.
JavaScript
async function fetchData() {
try {
const response = await fetch('https://fakestoreapi.com/products/100');
// Check if the response was successful
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the response body to JSON
const data = await response.json();
// Log the data
console.log(data);
} catch (error) {
// Handle any errors that occurred during the fetch
console.error('Error:', error);
}
}
// Call the async function
fetchData();
Handling Errors- Response validation: if (!response.ok) checks if the response status is between 200–299. If not, it's an error.
- Error throwing: If the response fails, throw new Error() is used with a custom message.
- Catching errors: .catch() handles errors like network issues or invalid responses.
- Handling invalid JSON: response.json() parses the response. If it fails, an error is thrown.
- Graceful error logging: Errors are logged using console.error() to avoid program crashes.
- Error: The thrown error ("item not found") occurs when the query parameter or item ID is missing, leading to an "unexpected end of JSON input" error.
Conclusion
The Fetch API provides a simple and modern way to make HTTP requests in JavaScript using promises. It replaces older methods like XMLHttpRequest and allows for clean handling of data retrieval, response parsing, and error management. Whether you use .then() or async/await, Fetch makes working with APIs easier and more readable. With proper status checks and error handling, it helps create reliable and user-friendly web applications.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read