Fetch API
This lesson explains Fetch API in JavaScript with beginner-friendly examples, practical use cases, and clear best practices.
JavaScript Fetch API Overview
The JavaScript Fetch API is a modern browser API used to make HTTP requests
from web applications. It allows developers to send and receive data from
servers, REST APIs, JSON endpoints, authentication services, form handlers,
and backend applications.
Fetch is promise-based and works well with async and
await. It is commonly used to load users, products, posts,
dashboard data, search results, file uploads, and form submissions in modern
frontend and full-stack JavaScript applications.
| Fetch Concept | Description | Common Usage |
| fetch() | Sends an HTTP request and returns a promise. | API calls and server requests. |
| Response | Represents the server response. | Status, headers, and body data. |
| response.json() | Reads response body as JSON. | REST API data. |
| HTTP Methods | Defines request action. | GET, POST, PUT, PATCH, DELETE. |
| Headers | Send metadata with requests. | Content-Type and Authorization. |
| Error Handling | Handles failed requests and invalid responses. | try...catch and response.ok. |
JavaScript Fetch API Example
async function getUsers() {
try {
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error("Failed to fetch users");
}
const users = await response.json();
console.log(users);
} catch (error) {
console.log(error.message);
}
}
getUsers();
This example uses fetch() with async and
await to load users from an API, check the response status,
parse JSON data, and handle errors.
Top 10 JavaScript Fetch API Examples
The following examples show the most common Fetch API patterns used in real
applications, including GET requests, POST requests, JSON parsing, headers,
authentication, and error handling.
| # | Example | Syntax |
| 1 | Basic GET Request | const response = await fetch("/api/users"); |
| 2 | Read JSON Response | const data = await response.json(); |
| 3 | POST JSON Data | fetch("/api/users", { method: "POST", body: JSON.stringify(user) }) |
| 4 | Send Headers | fetch("/api/users", { headers: { "Content-Type": "application/json" } }) |
| 5 | PUT Request | fetch("/api/users/1", { method: "PUT", body: JSON.stringify(user) }) |
| 6 | PATCH Request | fetch("/api/users/1", { method: "PATCH", body: JSON.stringify(update) }) |
| 7 | DELETE Request | fetch("/api/users/1", { method: "DELETE" }) |
| 8 | Check Response Status | if (!response.ok) { throw new Error("Request failed"); } |
| 9 | Authorization Header | fetch("/api/profile", { headers: { Authorization: "Bearer token" } }) |
| 10 | Upload FormData | fetch("/api/upload", { method: "POST", body: formData }) |
Popular Real-World Fetch API Examples
These examples show how the Fetch API is commonly used in production web
applications for data loading, authentication, forms, dashboards, search,
uploads, and CRUD operations.
| Scenario | Fetch Pattern |
| Load Users | const users = await fetch("/api/users").then(res => res.json()); |
| Load Product Details | const product = await fetch("/api/products/1").then(res => res.json()); |
| Submit Contact Form | await fetch("/api/contact", { method: "POST", body: JSON.stringify(formData) }); |
| Login Request | await fetch("/api/login", { method: "POST", body: JSON.stringify(credentials) }); |
| Authenticated Profile | await fetch("/api/profile", { headers: { Authorization: "Bearer token" } }); |
| Search Results | await fetch("/api/search?q=" + query); |
| Save Settings | await fetch("/api/settings", { method: "PUT", body: JSON.stringify(settings) }); |
| Delete Record | await fetch("/api/items/1", { method: "DELETE" }); |
| Upload File | await fetch("/api/upload", { method: "POST", body: formData }); |
| Handle Error Response | if (!response.ok) { showError("Unable to load data"); } |
Best Practices
- Use
async and await with fetch() for readable code. - Always check
response.ok before reading response data. - Use
try...catch to handle network errors. - Set
Content-Type when sending JSON data. - Use
JSON.stringify() when sending JavaScript objects as JSON. - Do not manually set
Content-Type when sending FormData. - Show loading, success, and error states in the UI.
- Never expose secret API keys or sensitive tokens in frontend code.
Common Mistakes
- Forgetting to call
response.json(). - Forgetting that
response.json() also returns a promise. - Not checking
response.ok for HTTP errors. - Sending JavaScript objects without
JSON.stringify(). - Manually setting JSON headers for
FormData uploads. - Ignoring loading and error states.
- Using frontend code to store private API secrets.
Key Takeaways
- The Fetch API is used to make HTTP requests in JavaScript.
fetch() returns a promise. response.json() reads JSON data and also returns a promise. - Use
GET, POST, PUT, PATCH, and DELETE for CRUD operations. - Always check
response.ok and handle errors properly. - Fetch API is essential for APIs, forms, dashboards, authentication, and full-stack apps.
Pro Tip
fetch() only rejects for network-level failures. For HTTP
errors like 404 or 500, check response.ok manually before
reading the response body.