How to Fetch Data from an API Using the Fetch API in JavaScript
The Fetch API
provides an easy way to make HTTP requests and retrieve data from a remote server. It's built into modern browsers and allows you to handle requests asynchronously, making it a great option for working with APIs in JavaScript.
In this tutorial, we’ll explore how to use the Fetch API
to retrieve data from an API and handle the response. We’ll cover basic usage, error handling, and working with JSON data.
1. Basic Fetch Request
The simplest use of the Fetch API
is to request data from an endpoint. The fetch()
function returns a promise that resolves to the Response
object representing the response to the request.
Example Code:
// Making a simple GET request to fetch data from an API
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => {
// Check if the response is OK (status code 200-299)
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse the JSON data from the response
})
.then(data => {
console.log(data); // Handle the fetched data (e.g., print to console)
})
.catch(error => {…