📖 JavaScript Intro to the Fetch API
The Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers. It's built on top of promises, making it easier to work with and more powerful compared to the older XMLHttpRequest object.
Methods of Fetching Data
There are three common methods of fetching data in JavaScript:
XMLHttpRequest
- An older way to make HTTP requests. It requires more code to handle requests and responses compared to modern methods.
fetch
API- A modern and more powerful way to make HTTP requests. It returns promises and is easier to use than
XMLHttpRequest
. - Axios
- A promise-based HTTP client for the browser and Node.js. It simplifies making HTTP requests and handling responses, and automatically transforms JSON data.
Note on Axios
While the Fetch API is a powerful tool for making HTTP requests, many developers also use libraries like Axios for more complex operations. Axios provides additional features such as request cancellation, automatic transformation of JSON data, and support for older browsers. We will explore Axios in a later unit.
Understanding JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is often used to transmit data between a server and web application. Here is an example of JSON data:
{
"name": "John",
"age": 30,
"city": "New York"
}
When you fetch data from a server, it is often returned in JSON format. You can then parse this JSON data to use it in your application.
Using JSONPlaceholder for Testing
For testing and prototyping, we will use jsonplaceholder.typicode.com
, a free online REST API that provides various endpoints returning dummy data. This is useful for practicing data fetching without needing a real server.
JSONPlaceholder is free to use. It provides several types of resources, such as:
/posts
- Returns a list of posts.
/comments
- Returns a list of comments.
/albums
- Returns a list of albums.
/photos
- Returns a list of photos.
/todos
- Returns a list of to-dos.
/users
- Returns a list of users.
To retrieve a specific item, you can add an ID to the endpoint, like /posts/1
to get the first post. For example:
https://jsonplaceholder.typicode.com/posts/1
Viewing JSON Data in the Browser
There are several ways to view JSON data returned to the browser:
- Console
- You can log the JSON data to the console using
console.log()
. Most browsers have a built-in developer console that you can open with F12 or right-clicking on the page and selecting "Inspect". - Browser Display
- Some browsers, like Google Chrome and Firefox, automatically format and display JSON data when you navigate directly to a URL that returns JSON. This makes it easier to read.
- Browser Extensions
- There are several browser extensions available, such as JSONView for Chrome and Firefox, that help format and display JSON data in a readable format.
- Online Tools
- You can use online JSON viewers and validators like JSON Formatter to paste your JSON data and view it in a readable format.
Making a GET Request
One of the most common uses of the Fetch API is to retrieve data from a server. A GET request is used to fetch data from a specified resource.
When working with the Fetch API, it's important to handle errors appropriately. Network requests can fail for various reasons, such as network issues, server errors, or invalid responses. By handling errors gracefully, you can improve the user experience and ensure your application behaves correctly even in adverse conditions.
fetch('https://jsonplaceholder.typicode.com/posts')
.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('Fetch error:', error));
In this example:
- The
fetch()
method makes a GET request to the specified URL. - The response is checked for success using the
response.ok
property. - If the response is successful, the response body is parsed as JSON using
response.json()
. - The parsed data is logged to the console.
- If an error occurs, it is caught and logged using
.catch()
.
Handling Responses
The Fetch API allows you to handle different types of responses. In most cases, data is returned in JSON format, but you might also encounter text, blobs, or other formats.
When dealing with JSON data, you can use the json()
method to parse the response:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
console.log('JSON data:', data);
// Handle JSON data here
})
.catch(error => console.error('Error fetching JSON data:', error));
In this example:
- The
fetch()
method makes a GET request to the specified URL. - The response body is parsed as JSON using
response.json()
. - The parsed JSON object is logged to the console.
- If an error occurs during parsing, it is caught and logged using
.catch()
.
Advanced Fetch with POST Requests
In addition to GET requests, the Fetch API can be used to send data to a server with POST requests. This is useful for submitting form data, creating new records, or performing other actions that require sending data.
const postData = { title: 'New Post', body: 'This is a new post', userId: 1 };
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(response => response.json())
.then(data => console.log('Post created:', data))
.catch(error => console.error('Error creating post:', error));
In this example:
method: 'POST'
specifies that the request should use the POST method.headers: { 'Content-Type': 'application/json' }
sets the request headers to indicate that the data being sent is in JSON format.body: JSON.stringify(postData)
converts the JavaScript object into a JSON string for sending in the request body.
Putting It Into Action
Create an HTML file with the following structure and include the provided script. This script will demonstrate how to fetch data from an API and log the results to the console.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch API Example</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
<div class="container mt-5">
<h1>Fetch API Example</h1>
</div>
<script>
fetch('https://jsonplaceholder.typicode.com/posts')
.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('Fetch error:', error));
</script>
</body>
</html>
Challenge
Modify the example to fetch and display a list of comments from the JSONPlaceholder API. Display the comments in the DOM instead of logging them to the console.
In order to check your learning, you should attempt to create a solution before revealing the provided solution below.
// JavaScript Code
fetch('https://jsonplaceholder.typicode.com/comments')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
const commentsList = document.createElement('ul');
data.forEach(comment => {
const listItem = document.createElement('li');
listItem.textContent = `${comment.name}: ${comment.body}`;
commentsList.appendChild(listItem);
});
document.body.appendChild(commentsList);
})
.catch(error => {
console.error('Fetch error:', error);
});