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
How to use JavaScript Fetch API to Get Data ? The Fetch API provides a JavaScript interface that enables users to manipulate and access parts of the HTTP pipeline such as responses and requests. Fetch API has so many rich and exciting options like method, headers, body, referrer, mode, credentials, cache, redirect, integrity, and a few more. H
2 min read
How to Fetch XML with Fetch API in JavaScript ? The JavaScript fetch() method retrieves resources from a server and produces a Promise. We will see how to fetch XML data with JavaScript's Fetch API, parse responses into XML documents, and utilize DOM manipulation for streamlined data extraction with different methods. These are the following meth
3 min read
How to Make GET call to an API using Axios in JavaScript? Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain JavaScript o
3 min read
How to connect to an API in JavaScript ? An API or Application Programming Interface is an intermediary which carries request/response data between the endpoints of a channel. We can visualize an analogy of API to that of a waiter in a restaurant. A typical waiter in a restaurant would welcome you and ask for your order. He/She confirms th
5 min read
What is the use of the Fetch API in JavaScript ? The Fetch API in JavaScript provides a modern, powerful, and flexible way to make HTTP requests from web browsers or Node.js environments. Its primary purpose is to facilitate fetching resources, typically data, from servers or other sources across the web. In simple terms, the Fetch API in JavaScri
2 min read