Posted January 24Jan 24 You are reading Part 19 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 3]IntroductionAPIs (Application Programming Interfaces) allow JavaScript applications to interact with external data sources, such as web services or databases. The fetch() function provides a modern way to make HTTP requests, replacing older methods like XMLHttpRequest.The fetch() API provides a powerful and modern way to interact with APIs in JavaScript. By mastering fetch requests, handling errors, and using async/await, developers can efficiently retrieve and send data to web services, making applications more dynamic and interactive.1. Using fetch() to Make API CallsThe fetch() function is used to send HTTP requests and retrieve data from an API. It returns a Promise that resolves to the Response object.Basic Syntax:fetch(url, options) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("Error fetching data:", error)); url: The API endpoint.options (optional): An object containing HTTP method, headers, and body..json(): Parses the response into a JavaScript object..catch(): Handles errors if the request fails.2. Fetching JSON Data from an APIExample: Getting Data from a Public APIfetch("https://jsonplaceholder.typicode.com/posts/1") .then(response => response.json()) .then(data => console.log("Fetched Post:", data)) .catch(error => console.error("Fetch error:", error)); Expected Output (Example JSON Response):{ "userId": 1, "id": 1, "title": "Sample Title", "body": "Sample Body" } 3. Handling Errors GracefullyNot all API requests succeed. Handling errors properly ensures a robust application.Example: Handling HTTP Errorsfetch("https://jsonplaceholder.typicode.com/invalid-endpoint") .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error("Fetch failed:", error.message)); 4. Making POST Requests with fetch()Fetching data is common, but APIs often require sending data (e.g., submitting forms, creating resources).Example: Sending Data Using POST Requestfetch("https://jsonplaceholder.typicode.com/posts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: "New Post", body: "This is a new post.", userId: 1 }) }) .then(response => response.json()) .then(data => console.log("Post Created:", data)) .catch(error => console.error("Error posting data:", error)); Expected Output:{ "title": "New Post", "body": "This is a new post.", "userId": 1, "id": 101 } 5. Using Async/Await with fetch()Async/Await provides a cleaner way to handle asynchronous fetch operations.Example:async function getData() { try { let response = await fetch("https://jsonplaceholder.typicode.com/users/1"); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } let data = await response.json(); console.log("User Data:", data); } catch (error) { console.error("Error fetching data:", error.message); } } getData(); 6. When to Use fetch() vs Other MethodsMethodUse Casefetch()Modern, recommended for making API requestsXMLHttpRequestLegacy method, not recommendedaxios (third-party)More feature-rich alternative to fetch()You are reading Part 19 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 3]
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.