Query a Web Server
Learning Objectives
- Master the fetch API
- Handle asynchronous operations
- Process JSON responses
- Handle errors gracefully
- Build data-driven applications
Section 23.1: Creating Asynchronous HTTP Requests
What is Asynchronous Programming?
Code continues running while waiting for a response.
The fetch() Function
fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
GET Request
// Simple GET
fetch("https://api.example.com/users")
.then(response => {
if (!response.ok) {
throw new Error("Network response failed");
}
return response.json();
})
.then(data => {
console.log("Data:", data);
})
.catch(error => {
console.error("Error:", error);
});
POST Request
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Alice",
email: "alice@example.com"
})
})
.then(response => response.json())
.then(data => console.log("Created:", data))
.catch(error => console.error("Error:", error));
Using Async/Await
async function getUsers() {
try {
let response = await fetch("https://api.example.com/users");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
getUsers();
Section 23.2: Handling JSON Data
Parsing JSON Response
fetch("/api/products")
.then(response => response.json()) // Parse JSON
.then(data => {
// Work with data
data.forEach(product => {
console.log(product.name);
});
});
Checking Response Status
fetch("/api/data")
.then(response => {
if (response.status === 200) {
return response.json();
} else if (response.status === 404) {
throw new Error("Data not found");
} else {
throw new Error("Server error");
}
})
.then(data => console.log(data))
.catch(error => console.error(error));
Accessing Response Headers
fetch("/api/data")
.then(response => {
console.log(response.headers.get("content-type"));
return response.json();
})
.then(data => console.log(data));
Coding Challenges
Challenge 22.1: Language List
Task: Fetch and display a list of languages from an API
Challenge 22.2: Famous Paintings
Task: Fetch artwork data and display paintings with details
Key Takeaways
✅ fetch() makes HTTP requests
✅ .then() handles responses
✅ response.json() parses JSON
✅ Async/await is cleaner syntax
✅ Always handle errors
✅ Check response.ok or status
Quiz Questions
- What does fetch() return?
- How do you send JSON data in a request?
- What is the difference between .then() and async/await?
- How do you check if a fetch was successful?
- What does response.json() do?
Next Module: Module 24 - Use Web APIs