1. What Is an API?
An API (Application Programming Interface)is a structured contract between two software systems. In web development, it's the set of URL endpoints and rules that allow your frontend application to request data from a backend server.
2. How APIs Work
Your browser or frontend app initiates the request (e.g., "fetch me the list of users").
Travels over the network with method (GET/POST), URL, headers, and optional body.
Processes the request, queries the database, and prepares the response data.
Returns HTTP status code (200, 404, 500) and JSON data payload back to the client.
3. What Is the Fetch API?
The fetch() function is the browser's built-in, modern, promise-based HTTP client. It replaced the older XMLHttpRequest (XHR) with a cleaner, more powerful interface.
const response = await fetch('https://api.example.com/users');
const data = await response.json();
console.log(data);
4. Making a GET Request With fetch()
const response = await fetch('https://api.example.com/users');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const users = await response.json();
return users;
}
5. Understanding the Response Object
| Property | Type | Description |
|---|---|---|
response.ok | boolean | true if status is 200-299 |
response.status | number | HTTP status code (200, 404, 500) |
response.statusText | string | "OK", "Not Found", "Internal Server Error" |
response.json() | Promise | Reads body stream and parses as JSON |
response.text() | Promise | Reads body stream as plain text |
6. Working With JSON
Converts a JavaScript object into a JSON string for sending in request bodies.
Converts a JSON string back into a JavaScript object for use in code.
7. Handling API Errors
fetch() Promise Rejects
No internet, DNS failure, CORS block — caught by try/catch.
fetch() Promise Resolves!
404, 500 — the promise still resolves. You must check response.ok manually.
fetch() does NOT reject on HTTP error codes (404, 500). It only rejects on actual network failures. Always check response.ok!8. POST Requests: Sending Data to the Server
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData)
});
const newUser = await response.json();
return newUser;
}
9. PUT, PATCH and DELETE Requests
| Method | Purpose | Body? |
|---|---|---|
| PUT | Replace entire resource | Yes (full object) |
| PATCH | Update specific fields | Yes (partial object) |
| DELETE | Remove the resource | Typically no |
10. Async/Await With fetch()
try {
const res = await fetch('/api/users');
if (!res.ok) throw new Error(`Status: ${res.status}`);
const data = await res.json();
renderUsers(data);
} catch (error) {
showError(error.message);
}
}
11. Loading, Success and Error States
Display a spinner or skeleton while isLoading === true.
Render data cards/tables when data arrives.
Show retry banners when error is caught.
12. Displaying API Data in the DOM
users.forEach(user => {
const card = document.createElement('div');
card.innerHTML = `<h3>${user.name}</h3><p>${user.email}</p>`;
container.append(card);
});
13. Query Parameters & URLSearchParams
category: 'tech',
page: '2',
limit: '10'
});
const url = `https://api.example.com/items?${params}`;
// ➔ https://api.example.com/items?category=tech&page=2&limit=10
14. API Headers & Authentication Basics
headers: {
'Authorization': 'Bearer eyJhbGciOiJI...',
'Content-Type': 'application/json',
'X-API-Key': 'your-api-key-here'
}
});
15. Practical API Project: User & Product Explorer
Use the interactive playground below to experiment with real API requests! Send GET requests to fetch users and products, POST new records, and simulate error scenarios.
16. Common Fetch & API Mistakes
- Assuming 404 rejects the promise:
fetch()only rejects on network failures. Always checkresponse.ok. - Forgetting the second
await:response.json()is an async operation and returns a Promise. - Missing Content-Type header on POST: The server won't parse the body as JSON without
'Content-Type': 'application/json'. - Not handling loading state: Users see a frozen UI without a spinner or skeleton indicator.
17. Fetch API Best Practices
- Always wrap fetch in
try/catchand checkresponse.okfor robust error handling. - Use
AbortControllerto cancel stale requests when the user navigates away or types rapidly. - Display loading, success, and error states for every API-driven UI component.
- Never hardcode API keys in frontend JavaScript — use environment variables or server-side proxies.