HTTP Requests in JavaScript with the Fetch API
The Fetch API is the built-in, promise-based HTTP client available in modern browsers and current JavaScript runtimes. It is a good default when you do not need a third-party request library.
This guide uses DummyJSON to demonstrate common CRUD-style requests.
Fetch All Products
const response = await fetch('https://dummyjson.com/products');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
console.log(data);Fetch a Product by ID
const response = await fetch('https://dummyjson.com/products/1');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(await response.json());Search Products
Use URLSearchParams when query values are dynamic:
const params = new URLSearchParams({ q: 'phone' });
const response = await fetch(`https://dummyjson.com/products/search?${params}`);
console.log(await response.json());Create a Product
const response = await fetch('https://dummyjson.com/products/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'BMW Pencil' }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(await response.json());Update a Product
const response = await fetch('https://dummyjson.com/products/1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Updated Product' }),
});
console.log(await response.json());Delete a Product
const response = await fetch('https://dummyjson.com/products/1', {
method: 'DELETE',
});
console.log(await response.json());DummyJSON simulates write operations; changes are not persisted as they would be in a real database-backed API.
Handle HTTP Errors Explicitly
fetch rejects its promise for network failures, but a 404 or 500 response does not reject automatically. Check response.ok or response.status yourself:
async function fetchProducts() {
const response = await fetch('https://dummyjson.com/products');
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
try {
const products = await fetchProducts();
console.log(products);
} catch (error) {
console.error(error);
}Cancellation with AbortController
const controller = new AbortController();
const request = fetch('/api/data', { signal: controller.signal });
controller.abort();Cancellation is useful when a component unmounts, a search query changes, or a request exceeds your own deadline.
Conclusion
The Fetch API handles ordinary HTTP work without extra dependencies. Check HTTP status codes explicitly, encode request bodies and query parameters carefully, and use AbortController when cancellation matters.