How To Use JavaScript Fetch API To Get Data?
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:
fetch('https://fakestoreapi.com/products/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

- 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.
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));

- 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.
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();

- 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.
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();

- 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.