Module 71 : Integrating with REST APIs in JavaScript
1. Introduction to REST APIs
What is an API?
API (Application Programming Interface) is a way for applications to talk to each other.
Example: A weather website fetches live weather data from an API instead of storing all data itself.
REST (Representational State Transfer)
REST is an architecture style for APIs that uses HTTP methods (GET, POST, PUT, DELETE) to interact with resources.
Data is usually exchanged in JSON format.
Why Use REST APIs in JavaScript?
JavaScript runs in browsers and servers (Node.js).
APIs let JavaScript apps fetch data (like tweets, weather info, or stock prices) or send data (like submitting a form).
2. HTTP Methods in REST APIs
GET → Retrieve data (e.g., fetch user list).
POST → Send data (e.g., create new user).
PUT/PATCH → Update existing data (e.g., edit user info).
DELETE → Remove data.
3. Making API Calls in JavaScript
3.1 Using fetch() (Modern Standard)
// Example: Fetching data from a REST API async function getUsers() { try { const response = await fetch("https://jsonplaceholder.typicode.com/users"); // Check if response is OK if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const users = await response.json(); console.log("Fetched Users:", users); } catch (error) { console.error("Error fetching users:", error.message); } } getUsers();
🔎 Explanation:
fetch() is built into modern browsers.
Returns a Promise → must use .then() or async/await.
Always check response.ok for errors.
Use .json() to convert response into usable JavaScript objects.
3.2 Using axios (Popular Library)
// Import axios (Node.js: install with npm install axios) import axios from "axios"; async function getPosts() { try { const response = await axios.get("https://jsonplaceholder.typicode.com/posts"); console.log("Fetched Posts:", response.data); } catch (error) { console.error("Error fetching posts:", error.message); } } getPosts();
🔎 Explanation:
axios simplifies API calls (no need to manually check .ok).
Automatically converts responses to JSON.
Handles errors more cleanly.
4. Sending Data with APIs
4.1 POST Request with fetch
async function createUser() { const newUser = { name: "John Doe", email: "john@example.com" }; try { const response = await fetch("https://jsonplaceholder.typicode.com/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(newUser), }); const data = await response.json(); console.log("User Created:", data); } catch (error) { console.error("Error creating user:", error.message); } } createUser();
🔎 Explanation:
method: "POST" → tells server we’re sending new data.
headers define content type (JSON).
body: JSON.stringify(object) → converts JS object into JSON string.
4.2 PUT & DELETE
// Update User async function updateUser(userId) { const updatedUser = { name: "Jane Doe" }; const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(updatedUser), }); const data = await response.json(); console.log("User Updated:", data); } // Delete User async function deleteUser(userId) { const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, { method: "DELETE" }); console.log("User Deleted:", response.status); } updateUser(1); deleteUser(1);
5. Handling Errors & Edge Cases

Network errors (no internet).
Server errors (500, 404).
Rate limits (too many requests).
Timeouts (server not responding).
👉 Always use try...catch or .catch() with Promises.
👉 Show user-friendly error messages.
6. Exercises
Exercise 1: Fetch & Display Posts
Fetch posts from https://jsonplaceholder.typicode.com/posts.
Display them in the console or DOM.
Exercise 2: Create a New Post
Send a POST request with a title and body.
Log the server response.
Exercise 3: Update and Delete
Update an existing post’s title.
Delete a post and confirm with response status.
Exercise 4: Error Handling
Try fetching from an invalid URL.
Catch and display the error message.
7. Advanced
7.1 Authentication
Many APIs require API keys or tokens.
async function fetchWithAuth() { const response = await fetch("https://api.example.com/data", { headers: { "Authorization": "Bearer YOUR_API_KEY_HERE" } }); const data = await response.json(); console.log(data); }
7.2 Async/Await vs Promises
// Promise way fetch("https://jsonplaceholder.typicode.com/users") .then(response => response.json()) .then(data => console.log("Promise Example:", data)) .catch(err => console.error(err)); // Async/Await way async function fetchAsync() { try { const res = await fetch("https://jsonplaceholder.typicode.com/users"); const data = await res.json(); console.log("Async/Await Example:", data); } catch (err) { console.error(err); } } fetchAsync();
8. Research Insights
REST vs GraphQL: REST fetches fixed resources, while GraphQL allows clients to specify exactly what data they need.
CORS (Cross-Origin Resource Sharing): Sometimes APIs block requests from other domains. You may need API keys or server-side proxies.
Rate Limits: Public APIs often limit how many requests you can make per minute/hour.
9. Start with the concept of APIs using analogy (e.g., waiter taking orders = API).
Show a live demo of fetching users from jsonplaceholder.typicode.com.
Gradually move from GET → POST → PUT → DELETE.
Encourage to modify examples and run them in browser console or Node.js.
Assign exercises at the end.
Understand REST APIs.
Perform GET, POST, PUT, DELETE operations.
Handle errors properly.
Work with fetch() and axios.
Prepare for APIs (authentication, rate limits).
No comments:
Post a Comment