Async JavaScript: Promises, Async/Await, and Fetch APILesson 7.3
The Fetch API and HTTP Requests
fetch(), GET requests, POST requests, request options, reading response, handling errors, working with JSON APIs
The Fetch API and HTTP Requests
The Fetch API is the modern way to make HTTP requests from JavaScript. It replaces the older XMLHttpRequest and works with Promises natively, making it a perfect partner for async/await. In this lesson you will learn how to GET data from an API and POST data to a server.
Making a GET Request
async function getPost(id) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const post = await response.json();
console.log('Title:', post.title);
console.log('Body:', post.body);
return post;
} catch (error) {
console.error('Fetch error:', error.message);
}
}
getPost(1);Making a POST Request
async function createPost(data) {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`Failed to create post: ${response.status}`);
}
const result = await response.json();
console.log('Created post with ID:', result.id);
return result;
} catch (error) {
console.error('Error:', error.message);
}
}
createPost({
title: 'My New Post',
body: 'This is the post content.',
userId: 1
});Displaying API Data in the DOM
async function renderUsers() {
const container = document.querySelector('#users-list');
container.innerHTML = '<p>Loading...</p>';
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await response.json();
container.innerHTML = users.map(user =>
`<div class="user-card">
<h3>${user.name}</h3>
<p>${user.email}</p>
<p>${user.address.city}</p>
</div>`
).join('');
} catch (error) {
container.innerHTML = '<p>Failed to load users. Please try again.</p>';
console.error(error);
}
}
renderUsers();