How To Use JavaScript Fetch API To Get Data?
An API is a set of rules, protocols, and tools that allows different software applications to communicate with each other. One of the popular ways to perform API requests in JavaScript is by using Fetch API.
What is the Fetch API?
The Fetch API is a built-in JavaScript feature that allows you to make HTTP requests. It is a modern alternative to XMLHttpRequest and provides a cleaner, more powerful way to interact with APIs.
Syntax
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error)
- 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
- Sending a Request: The fetch() function sends a request to a server to retrieve or send data.
- Returns a Promise: Fetch works asynchronously and returns a Promise. It either resolves with data or catches an error.
- Checking the Response: Use response.ok to check if the request was successful. If not, handle errors accordingly.
- Parsing the Data: If successful, convert the response into a usable format like JSON using response.json().
- Handling Errors: Use .catch() to handle errors (like network issues or invalid responses) to prevent crashes.
Using JavaScript Fetch API To Get Data
To fetch data from an API using the Fetch API, you simply call fetch() with the API URL. Here’s a basic example.
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.
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.
async function fetchData() {
const response = await fetch('https://fakestoreapi.com/products/1');
const data = await response.json();
console.log(data);
}
fetchData();

Using async/await with Fetch API
- async function: The fetchData function is marked as async, enabling the use of await inside it to handle asynchronous operations.
- await fetch(): The await keyword pauses the function execution until the fetch request is completed and the response is received.
- await response.json(): After receiving the response, await is used to parse the response body into JSON format.
- Logging the data: The data is then logged to the console after being successfully fetched and parsed.
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.
fetch('https://fakestoreapi.com/products/100')
.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 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.