Fetch API and REST API Integration in JavaScript
Quick Answer: The Fetch API lets JavaScript send HTTP requests and receive responses from a server. A REST API provides endpoints for reading, creating, updating and deleting data. Together, they help web applications exchange data without reloading the page.
We will connect a mobile shop application to a product API. You will learn GET, POST, PUT, PATCH and DELETE with practical examples.
1. What Are Fetch API and REST API?
Imagine Ravi manages a mobile shop in Bengaluru. His website displays mobile phones and their prices.
Customers expect the latest product information. Ravi also needs to add products and update prices.
JavaScript can handle the page. But where does the product information come from?
The server stores and manages that information. The browser needs a way to communicate with it.
What Is an API?
API = a set of rules that lets software communicate.
A website can request information through an API. The server processes the request and sends a response.
What Is a REST API?
REST = a style for designing web APIs around resources.
A resource is something the application manages. In Ravi's shop, a product is one resource.
A REST API commonly uses HTTP methods to describe the required action.
Example product endpoints
GET /products — Read the product list
POST /products — Create a product
PUT /products/1 — Replace a product
PATCH /products/1 — Update selected fields
DELETE /products/1 — Delete a product
What Is the Fetch API?
Fetch API = the browser feature used to make HTTP requests.
It is built into modern browsers. You do not need jQuery or another library.
Fetch returns a Promise. A Promise represents a result that may arrive later.
We usually use async and await to handle that result clearly.
2. The Problem: Managing Products Without an API
Imagine Ravi manages 1,000 products across several shop branches. How will every branch receive the latest prices?
Think about maintaining the same product list on every page. What happens when a price changes?
Here is a small example without an API.
Example 1: Store product information directly in JavaScript
This code works for a small, fixed product list.
const products = [
{ id: 1, name: "Samsung Galaxy", price: 25000 },
{ id: 2, name: "iPhone", price: 55000 },
{ id: 3, name: "OnePlus", price: 35000 }
];
products.forEach(product => {
console.log(product.name + " - Rs. " + product.price);
});
Expected output
Samsung Galaxy - Rs. 25000 iPhone - Rs. 55000 OnePlus - Rs. 35000
This works, but it gets hard to manage as products grow.
What Goes Wrong?
- Every page may contain a separate product list.
- Price changes need manual updates in multiple places.
- Different branches may display different product details.
- Customers cannot see newly added products automatically.
- Maintaining thousands of products becomes difficult.
Now think about 1,000 products and several shop branches. A shared server-side source becomes important.
3. The Solution: Connect JavaScript to a REST API
Instead of keeping product data inside JavaScript, we request it from a server.
For learning, we will use DummyJSON. It provides sample product endpoints.
Learning API: https://dummyjson.com/products
DummyJSON is a sample API for development and practice. Its write operations simulate changes. Do not use it as a real shop database.
Our application will request a product. The server will return JSON data.
JSON = a text format used to exchange structured data.
How the Request Travels
The animation highlights each stage of a request, from the browser to the server and back.
Step 1: Make a GET Request
GET = request information from the server.
We will request one product using its ID. The API returns a JSON response.
Example 2: Fetch one product from the API
This example reads product details and prints the result.
async function getProduct() {
try {
const response = await fetch(
"https://dummyjson.com/products/1"
);
if (!response.ok) {
throw new Error("Unable to load product");
}
const product = await response.json();
console.log("Product:", product.title);
console.log("Price:", product.price);
} catch (error) {
console.error("Request failed:", error.message);
}
}
getProduct();
Expected output for the sample product
Product: iPhone 9 Price: 549
Important: The response is asynchronous. The browser does not stop all other work while waiting. The await keyword waits inside the async function.
Step 2: Understand the Response
The server returns a response object first. We then check its status.
Calling response.json() reads the response body. It also returns a Promise.
The parsed object contains the product fields. We can use those fields in our application.
Example 3: Inspect the response object
async function inspectProduct() {
const response = await fetch(
"https://dummyjson.com/products/1"
);
console.log("HTTP status:", response.status);
console.log("Request successful:", response.ok);
const data = await response.json();
console.log("Product title:", data.title);
}
inspectProduct();
Expected output
HTTP status: 200 Request successful: true Product title: iPhone 9
Step 3: Fetch Multiple Products
Ravi also needs a product list for the shop page.
We can request several products through one endpoint.
Example 4: Read a product collection
async function getProducts() {
try {
const response = await fetch(
"https://dummyjson.com/products?limit=3"
);
if (!response.ok) {
throw new Error("Unable to load products");
}
const result = await response.json();
result.products.forEach(product => {
console.log(product.title, product.price);
});
} catch (error) {
console.error(error.message);
}
}
getProducts();
Expected output format
Product title 1 Product price 1 Product title 2 Product price 2 Product title 3 Product price 3
The exact product values come from the API response. The example prints the first three returned products.
4. Send Data Using POST
GET reads information. POST sends new information to the server.
Ravi wants to add a new mobile phone to his product catalog.
The request needs an HTTP method and a JSON body.
Example 5: Create a product using POST
async function addProduct() {
const newProduct = {
title: "Samsung Galaxy S25",
price: 79999,
category: "smartphones"
};
try {
const response = await fetch(
"https://dummyjson.com/products/add",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(newProduct)
}
);
if (!response.ok) {
throw new Error("Unable to create product");
}
const result = await response.json();
console.log("Created product:", result);
} catch (error) {
console.error(error.message);
}
}
addProduct();
Expected output format
Created product:
{
id: generated product id,
title: "Samsung Galaxy S25",
price: 79999,
category: "smartphones"
}
JSON.stringify converts a JavaScript object into JSON text.
Remember: DummyJSON simulates the create operation. It does not permanently save your product. A real shop needs its own backend and database.
5. Update Data Using PUT and PATCH
Ravi may need to change a product's price. REST APIs commonly support two update methods.
PUT = replace the resource with the supplied representation.
PATCH = change selected fields of an existing resource.
Update a Product Using PUT
Example 6: Replace product information
async function replaceProduct() {
const updatedProduct = {
title: "Samsung Galaxy S25 Ultra",
price: 99999,
category: "smartphones"
};
const response = await fetch(
"https://dummyjson.com/products/1",
{
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(updatedProduct)
}
);
if (!response.ok) {
throw new Error("Product update failed");
}
const result = await response.json();
console.log(result);
}
replaceProduct().catch(console.error);
Expected output
Updated product response Title: Samsung Galaxy S25 Ultra Price: 99999
Update Selected Fields Using PATCH
Sometimes Ravi only needs to change the price. PATCH helps send only that field.
Example 7: Change only the product price
async function updateProductPrice() {
const response = await fetch(
"https://dummyjson.com/products/1",
{
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ price: 599 })
}
);
if (!response.ok) {
throw new Error("Price update failed");
}
const result = await response.json();
console.log("Updated price:", result.price);
}
updateProductPrice().catch(console.error);
Expected output
Updated price: 599
Both examples use a sample API. Their simulated updates are not permanent.
6. Delete Data Using DELETE
Ravi may remove a discontinued product from the catalog.
DELETE = ask the server to remove a resource.
Example 8: Delete a product
async function deleteProduct() {
try {
const response = await fetch(
"https://dummyjson.com/products/1",
{
method: "DELETE"
}
);
if (!response.ok) {
throw new Error("Product deletion failed");
}
const result = await response.json();
console.log("Deletion response:", result);
} catch (error) {
console.error(error.message);
}
}
deleteProduct();
Expected output format
Deletion response:
{
id: 1,
isDeleted: true,
deletedOn: "server timestamp"
}
The sample API simulates deletion. A real backend controls permanent deletion.
7. Understand the Complete REST Request Flow
Each HTTP method describes a different operation. The browser sends the request through Fetch.
This animation follows the request from its HTTP method to the server response.
HTTP Methods at a Glance
| Method | Purpose | Shop example |
|---|---|---|
| GET | Read data | Show mobile phones |
| POST | Create data | Add a new phone |
| PUT | Replace a resource | Replace product details |
| PATCH | Update selected fields | Change a product price |
| DELETE | Delete a resource | Remove a discontinued phone |
8. Important Parts of a Fetch Request
Fetch accepts a URL and an optional configuration object.
The configuration controls the method, headers, body and other request settings.
| Option | Meaning | Example |
|---|---|---|
| method | HTTP operation | GET, POST, PATCH |
| headers | Extra request information | Content-Type |
| body | Data sent to the server | JSON.stringify(data) |
| signal | Controls request cancellation | AbortController |
| credentials | Controls credential handling | include, same-origin |
Understand HTTP Headers
Headers = extra information sent with an HTTP request or response.
For JSON requests, we commonly send a Content-Type header.
Content-Type: application/json tells the server that the request body contains JSON.
Some APIs also expect an Authorization header. It may contain a token or another credential.
Understand HTTP Status Codes
The server uses status codes to describe the result.
| Status | Meaning | Typical situation |
|---|---|---|
| 200 | OK | Request completed successfully |
| 201 | Created | Resource created successfully |
| 204 | No Content | Request succeeded without a response body |
| 400 | Bad Request | Request data is invalid |
| 401 | Unauthorized | Authentication is missing or invalid |
| 403 | Forbidden | User is not allowed to perform the action |
| 404 | Not Found | Resource does not exist |
| 500 | Internal Server Error | Server encountered an error |
Important: Fetch does not reject its Promise for HTTP errors such as 404 or 500. Check response.ok or response.status yourself.
9. Handle Errors and Network Problems
API requests can fail for different reasons. The server may be unavailable or the network may disconnect.
We should handle these cases. We should also show a useful message to the user.
Example 9: Handle HTTP errors and network failures
async function loadShopProduct() {
try {
const response = await fetch(
"https://dummyjson.com/products/1"
);
if (response.status === 404) {
throw new Error("Product was not found");
}
if (!response.ok) {
throw new Error(
"Server error: " + response.status
);
}
const product = await response.json();
console.log(product.title);
} catch (error) {
console.error("Unable to load product:", error.message);
}
}
loadShopProduct();
Possible output when the request succeeds
iPhone 9
Possible output when the request fails
Unable to load product: Failed to fetch
Cancel a Request with AbortController
Sometimes a user leaves a page before its request finishes. We may want to cancel that request.
AbortController = a browser feature for cancelling supported operations.
Example 10: Cancel a slow request
async function loadWithTimeout() {
const controller = new AbortController();
const timeoutId = setTimeout(() => {
controller.abort();
}, 5000);
try {
const response = await fetch(
"https://dummyjson.com/products/1",
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Request failed");
}
const product = await response.json();
console.log(product.title);
} catch (error) {
if (error.name === "AbortError") {
console.log("Request was cancelled");
} else {
console.error(error.message);
}
} finally {
clearTimeout(timeoutId);
}
}
loadWithTimeout();
Possible output
iPhone 9
If the request takes too long, the controller cancels it. The catch block handles that cancellation.
10. Complete Product API Integration Example
Now we can combine the important parts. This example loads products and handles errors.
It uses a small browser page. You can place the HTML and JavaScript in a local file.
Example 11: Complete product listing page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mobile Shop Products</title>
</head>
<body>
<h1>Mobile Shop</h1>
<p id="status">Loading products...</p>
<ul id="productList"></ul>
<script>
async function loadProducts() {
const status = document.getElementById("status");
const list = document.getElementById("productList");
try {
const response = await fetch(
"https://dummyjson.com/products?limit=5"
);
if (!response.ok) {
throw new Error("Unable to load products");
}
const data = await response.json();
list.replaceChildren();
data.products.forEach(product => {
const item = document.createElement("li");
item.textContent =
product.title + " - Rs. " + product.price;
list.appendChild(item);
});
status.textContent = "Products loaded successfully";
} catch (error) {
status.textContent = error.message;
}
}
loadProducts();
</script>
</body>
</html>
Expected page behaviour
Mobile Shop Products loaded successfully Product title 1 - Product price 1 Product title 2 - Product price 2 Product title 3 - Product price 3 Product title 4 - Product price 4 Product title 5 - Product price 5
The page creates list items from the returned data. It does not need a page reload for this request.
Security note: We used textContent for product names. Avoid inserting untrusted API data through innerHTML. That can expose your page to HTML injection and cross-site scripting.
11. Common Mistakes and Best Practices
Mistake 1: Forgetting to Check response.ok
Fetch can return a response for HTTP errors. A 404 response does not automatically enter the catch block.
Better approach: Check the response before reading its data.
Correct approach
const response = await fetch(url);
if (!response.ok) {
throw new Error("Request failed");
}
const data = await response.json();
Mistake 2: Forgetting JSON.stringify
Passing a JavaScript object directly as the request body is incorrect.
Better approach: Convert the object into JSON text.
Correct approach
body: JSON.stringify({
title: "Samsung Galaxy",
price: 79999
})
Mistake 3: Forgetting the Content-Type Header
Some servers need to know the format of the request body.
Better approach: Set the JSON content type when sending JSON.
Correct approach
headers: {
"Content-Type": "application/json"
}
Mistake 4: Exposing Secret API Keys
Browser JavaScript is visible to users. Never store private server credentials in frontend code.
Better approach: Keep private keys on your backend. Let the backend call protected services.
Mistake 5: Ignoring Loading and Error States
Users need feedback while the request is running. They also need a useful message when it fails.
Better approach: Show loading, success and error states.
Mistake 6: Sending Too Many Requests
Repeated requests can slow the application. They may also increase server load.
Better approach: Use pagination, caching and request cancellation where appropriate.
12. Architecture and Real-World Trade-Offs
A browser can call an API directly. That is useful for public data and simple applications.
However, enterprise applications often use a backend between the browser and external services.
The animation follows a request through the backend, security checks and data services.
Why Use a Backend API?
- Security: Private API keys stay on the server.
- Validation: The backend checks incoming data.
- Access control: The backend checks user permissions.
- Business rules: Important rules stay outside the browser.
- Integration: The backend can connect databases and other services.
Understand CORS
CORS = browser rules that control cross-origin requests.
A different origin means a different scheme, host or port. The API server must allow the browser's origin.
When CORS is not configured correctly, the browser may block JavaScript from reading the response.
Important: Adding a request header in JavaScript does not fix server-side CORS settings. Configure the API server to allow the required origin and headers.
Production Best Practices
- Use HTTPS for requests and responses.
- Keep private credentials on the backend.
- Validate data on the server, not only in the browser.
- Use pagination for large product collections.
- Set sensible request timeouts and cancellation rules.
- Handle network failures and HTTP errors separately.
- Use caching when the data and freshness rules allow it.
- Log useful server-side details without exposing secrets.
- Do not assume a successful browser request means a database transaction is permanent.
13. Fetch API vs Axios
Fetch is built into modern browsers. Axios is a separate HTTP client library.
| Feature | Fetch API | Axios |
|---|---|---|
| Installation | No package needed in modern browsers | Install or include the package |
| JSON parsing | Call response.json() | Response data is usually parsed automatically |
| HTTP errors | Check response.ok | Non-success status codes reject by default |
| Request cancellation | AbortController | AbortController in current versions |
| Interceptors | Not built in | Supported |
| Dependencies | Browser built-in | External library |
Fetch is a good starting point for learning browser networking. Axios can help when an application needs shared request configuration or interceptors.
14. Interview Questions and Answers
Question 1: What Is the Fetch API?
What the interviewer wants: They want to know how you call an API from JavaScript.
Strong answer:
"Fetch is a browser API for making HTTP requests. It returns a Promise. I use async and await to handle the response. I also check response.ok and handle network errors."
Question 2: What Is the Difference Between Fetch and a REST API?
Strong answer:
"Fetch is the JavaScript feature that sends HTTP requests. REST is an architectural style for designing APIs. Fetch can call REST APIs, but it can also call other HTTP endpoints."
Question 3: Does Fetch Throw an Error for a 404 Response?
Strong answer:
"No. Fetch normally resolves with a Response object for HTTP errors. I check response.ok or the status code. Network failures and request aborts are handled through catch."
Question 4: What Is the Difference Between PUT and PATCH?
Strong answer:
"PUT is generally used to replace a resource. PATCH is used to change selected fields. In Ravi's shop, PUT can replace product details. PATCH can change only its price."
Question 5: What Is CORS?
Strong answer:
"CORS is a browser security mechanism for cross-origin requests. The API server sends headers that allow specific origins. If the server does not allow the browser's origin, JavaScript cannot read the response."
Question 6: How Would You Improve API Performance?
Strong answer:
"I would first check the request volume and response time. I would use pagination for large product lists. I would also use caching where it is safe. For repeated requests, I would consider cancellation and request deduplication."
15. Hands-On Practice
Use the mobile shop example for your first exercise. Then try the other business scenarios.
Beginner Exercises
- Fetch product ID 2 and print its title.
- Fetch five products and print their prices.
- Check the HTTP status before reading the response.
Hint: Start with fetch(), then call response.json().
Intermediate Exercises
- Create a product using POST.
- Update a product price using PATCH.
- Delete a product and inspect the response.
- Display a loading message while products load.
- Show a useful error message when the API fails.
Hint: Use the request configuration object. Add the method, headers and body where needed.
Advanced Exercises
- Build a product search page using query parameters.
- Add pagination to the product list.
- Cancel a request when the user starts a new search.
- Build a reusable function for common API requests.
- Connect a real backend and store products in a database.
Architect-level challenge: Design a shared API client for a large shop application. Include authentication, error handling, logging, retries and request cancellation. Explain which responsibilities belong in the browser and which belong on the backend.
16. Frequently Asked Questions
Can I use Fetch without installing a package?
Yes. Fetch is built into modern browsers. You can call it directly from JavaScript.
Can Fetch call a .NET Web API?
Yes. A browser can call an ASP.NET Core Web API through HTTP. The API must allow the browser origin when cross-origin access is needed.
Does Fetch support POST and DELETE?
Yes. Set the method in the request configuration. You can also provide headers and a request body when needed.
Can Fetch work with authentication?
Yes. You can send an authorization header when the API expects one. Keep private credentials out of browser code.
Is Fetch available in Node.js?
Modern Node.js versions include a built-in Fetch implementation. Check the Node.js version used by your project.
What happens when the server returns an empty response?
Some successful responses use status 204. Do not call response.json() when the response has no JSON body.
17. Next Steps and Community
You now know how JavaScript communicates with REST APIs. You have also learned how to read and change server data.
Explore Further
- MDN: Fetch API — Learn about browser request handling.
- MDN: Response — Understand HTTP response objects.
- MDN: AbortController — Learn how to cancel requests.
- DummyJSON: Product API — Practise with sample product endpoints.
Share Your Knowledge
Try these examples and build a small product application. Share your implementation and explain your design choices.
Discuss alternative approaches and help other developers learn. Practical examples make these concepts easier to understand.
Learn Technology. Build Your Future.
Upgradix by Shrash Studio — Quality Technology Education. Completely Free.