55 Mins upper-intermediate
18. Fetch API & JSON
Async
Fetch API & APIs
Modern frontend applications rely on APIs to get data from a backend server. The native fetch() API is how JavaScript makes HTTP requests to the internet.
📡 Making a GET Request
Fetch returns a Promise. Because fetching from a server takes time, we use async/await to wait for the response, and then parse the raw text into a JSON object.
// Note: In this sandbox, we simulate the fetch delay
const mockFetch = async () => {
return { json: async () => ({ title: "Learn JavaScript", completed: false }) };
};
const getTodo = async () => {
try {
// In reality: await fetch("https://jsonplaceholder.typicode.com/todos/1")
const response = await mockFetch();
const data = await response.json();
console.log("Todo Task:", data.title);
} catch (error) {
console.error("Failed to fetch data", error);
}
};
getTodo();
OutputTodo Task: Learn JavaScript
📦 Working with JSON
JSON (JavaScript Object Notation) is the standard format for transferring data across the web. JavaScript provides two native methods to handle it.
const userObj = { name: "Ama", age: 28 };
// Convert JS Object into a JSON String (to send to a server)
const jsonString = JSON.stringify(userObj);
console.log("Stringified:", jsonString);
// Convert JSON String back into a JS Object (received from a server)
const parsedObj = JSON.parse(jsonString);
console.log("Parsed Name:", parsedObj.name);
OutputStringified: {"name":"Ama","age":28}
Parsed Name: Ama
Parsed Name: Ama
Knowledge Check
Ready to test your understanding of 18. Fetch API & JSON?