LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
JavaScript

Build a Real-World JavaScript Application Using APIs and DOM

JavaScript, an API and DOM manipulation. An API (Application Programming Interface) allows our application to communicate with another service and receive data. The DOM (Document Object Model) represents the webpage as elements that JavaScript can access and update. We use these concepts in weather applications, shopping websites, dashboards and many other projects.

Build a Real-World JavaScript Application Using APIs and the DOM

Quick Answer: JavaScript can fetch data from an API and display it inside a web page. The Fetch API sends HTTP requests. The DOM helps us create and update page elements. We will build a product search application using both.

1. The Problem: Managing Product Information

Imagine you manage an online shop with 10,000 products. Customers want to search for products quickly. How will your website show the latest product information?

One option is to write every product directly inside HTML. That works for a few products. It becomes difficult when the product list changes often.

Without an API: Writing Products Directly

API = a way for two applications to exchange data.

DOM = the browser's object model for a web page.

Consider this small product list. Every new product needs another HTML element.

Example 1: Hard-coded shop products

const products = [
  { name: "Wireless Mouse", price: 599 },
  { name: "Mechanical Keyboard", price: 2499 },
  { name: "USB-C Hub", price: 1299 }
];

const list = document.getElementById("products");

products.forEach((product) => {
  const item = document.createElement("li");
  item.textContent = product.name + " - Rs. " + product.price;
  list.append(item);
});

Expected output

Wireless Mouse - Rs. 599
Mechanical Keyboard - Rs. 2499
USB-C Hub - Rs. 1299

This works, but the product information lives inside our code.

What Goes Wrong as the Shop Grows?

  1. Developers must change code when products change.
  2. The same product data may appear in many pages.
  3. Users cannot search the latest server-side product list.
  4. Large lists make manual HTML updates difficult.
  5. Product data and page design become tightly connected.

Now imagine updating 10,000 products across several shop pages. We need a better approach.

With an API: Load Products When Needed

The shop can request product data from a server. The server returns JSON. JavaScript reads that data and updates the page.

JSON = a text format used to exchange structured data.

Hard-coded data compared with API data
Without an API With an API
Products are written in application code. Products come from a server.
Updates need code changes. Server data can change independently.
Search uses the local list. Search can request matching server data.
Each page may repeat product data. Several pages can use the same API.
Large lists are harder to maintain. Data can be loaded when needed.

The idea to remember

  • API = a service that provides or receives data.
  • Fetch = the browser method used to make HTTP requests.
  • JSON = the data format returned by our example API.
  • DOM = the browser's representation of the page.
  • Element = one HTML item, such as a heading or button.
  • Event = an action, such as typing or clicking.
  • Async = work that can finish later without blocking the page.

2. What We Are Going to Build

We will build a product search page for an online shop. Customers can search by product name. The page will request matching products from an API.

Our application will support these features:

  • Search products using a text field.
  • Load matching products from the server.
  • Display product names, prices and categories.
  • Show loading and error messages.
  • Show a message when no products match.
  • Prevent older requests from replacing newer results.

We will use the public DummyJSON products API for this learning example.

Version and API note: This example uses modern browser JavaScript. It needs a browser with Fetch API and async/await support. DummyJSON is a sample API, not a production shop database.

3. Understand the Application Flow

First, follow the complete journey from the search box to the product cards.

1. Search input Customer enters a product name 2. JavaScript Fetch Browser sends an HTTP request 3. Products API Server finds matching products 4. JSON response JavaScript reads the response data 5. DOM rendering Product cards appear on the page

Animation 1: The request travels from the search field to the API, then returns as DOM content.

The browser starts the request. The API processes it and sends JSON. JavaScript creates page elements from the response.

4. Prepare the Project

Create a folder named shop-product-search. Add these three files.

shop-product-search/
  index.html
  styles.css
  app.js

No package installation is needed. We are using browser features only.

Step 1: Create the HTML

HTML provides the search field and the product display area. JavaScript will find these elements using their IDs.

Example 2: index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Shop Product Search</title>
  <link rel="stylesheet" href="styles.css">
  <script src="app.js" defer></script>
</head>
<body>
  <main class="shop">
    <h1>Find Products</h1>
    <p>Search the shop product catalogue.</p>

    <label for="searchInput">Product name</label>
    <input
      id="searchInput"
      type="search"
      placeholder="Try phone, laptop or perfume"
      autocomplete="off"
    >

    <p id="status" role="status" aria-live="polite">
      Enter a product name to search.
    </p>

    <section id="productList"
      class="product-grid"
      aria-label="Search results">
    </section>
  </main>
</body>
</html>

Step 2: Add the page styles

CSS controls the layout and appearance. The grid adjusts to different screen sizes.

Example 3: styles.css

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 32px 16px;
  background: #f1f5f9;
  color: #172033;
  font-family: Arial, sans-serif;
}

.shop {
  max-width: 1000px;
  margin: 0 auto;
}

.shop h1 {
  margin-bottom: 8px;
}

#searchInput {
  width: 100%;
  max-width: 520px;
  padding: 13px;
  margin: 8px 0 16px;
  border: 1px solid #94a3b8;
  border-radius: 8px;
  font-size: 16px;
}

#status {
  min-height: 28px;
  color: #334155;
}

.product-grid {
  display: grid;
  grid-template-columns:
    repeat(auto-fit, minmax(210px, 1fr));
  gap: 16px;
}

.product-card {
  padding: 16px;
  background: #ffffff;
  border: 1px solid #dbe2ea;
  border-radius: 10px;
}

.product-card h2 {
  font-size: 18px;
  margin: 0 0 10px;
}

.product-card p {
  margin: 6px 0;
}

.product-price {
  color: #166534;
  font-weight: 700;
}

Step 3: Connect to the API

Now we will write the main JavaScript application. It will search the API and build product cards.

We will use this endpoint:

https://dummyjson.com/products/search?q=phone

The API accepts a search term through the q query parameter. It returns a JSON object containing a products array.

Example 4: app.js — complete application

const searchInput = document.getElementById("searchInput");
const productList = document.getElementById("productList");
const status = document.getElementById("status");

let debounceTimer;
let activeController;

function setStatus(message) {
  status.textContent = message;
}

function clearProducts() {
  productList.replaceChildren();
}

function createProductCard(product) {
  const card = document.createElement("article");
  card.className = "product-card";

  const title = document.createElement("h2");
  title.textContent = product.title;

  const category = document.createElement("p");
  category.textContent = "Category: " + product.category;

  const price = document.createElement("p");
  price.className = "product-price";
  price.textContent = "Price: $" + product.price;

  card.append(title, category, price);
  return card;
}

function renderProducts(products) {
  const fragment = document.createDocumentFragment();

  products.forEach((product) => {
    fragment.append(createProductCard(product));
  });

  productList.replaceChildren(fragment);
}

async function searchProducts(query) {
  if (!query) {
    clearProducts();
    setStatus("Enter a product name to search.");
    return;
  }

  if (activeController) {
    activeController.abort();
  }

  activeController = new AbortController();
  const signal = activeController.signal;

  clearProducts();
  setStatus("Loading products...");

  try {
    const url =
      "https://dummyjson.com/products/search?q=" +
      encodeURIComponent(query);

    const response = await fetch(url, { signal });

    if (!response.ok) {
      throw new Error("Unable to load products.");
    }

    const data = await response.json();
    const products = data.products || [];

    if (products.length === 0) {
      setStatus("No matching products found.");
      return;
    }

    renderProducts(products);
    setStatus(
      products.length + " product(s) found."
    );
  } catch (error) {
    if (error.name === "AbortError") {
      return;
    }

    setStatus(error.message);
  }
}

searchInput.addEventListener("input", () => {
  clearTimeout(debounceTimer);

  const query = searchInput.value.trim();

  debounceTimer = setTimeout(() => {
    searchProducts(query);
  }, 400);
});

Expected application behaviour

Customer searches: phone
Loading products...
API returns matching products.
Product cards appear on the page.
Status: 5 product(s) found.

Customer searches: an-unavailable-product
Loading products...
Status: No matching products found.

Important: The number of results depends on the API response. The output above describes an example interaction. It is not a fixed result count.

5. Understand the Second Animation: Search and Request Handling

Searching is more than sending a request. The application also waits, cancels old work and handles the response.

Customer types a search The input event runs Debounce timer Wait briefly after typing stops Fetch and cancellation Send request or abort older request Show the latest result Render cards or show a message

Animation 2: The search lifecycle highlights the wait, request handling and final result stages.

This second flow focuses on user input and request control. It is different from the API data-flow diagram.

6. Step-by-Step Code Breakdown

1. Select the HTML elements

getElementById() finds an element using its ID. We keep these references for later updates.

2. Listen for user input

addEventListener() runs a function when an event happens. Here, the event is input.

3. Wait before searching

Debounce = waiting briefly before running repeated work. We use 400 milliseconds in this example. Each new keystroke resets the timer.

4. Send the HTTP request

fetch() sends a request to the API. It returns a Promise, which represents work that finishes later.

5. Read the JSON response

response.json() reads the response body. We use await to wait for that result.

6. Create DOM elements

createElement() creates new HTML elements. We set their text and add them to the product area.

7. Handle older requests

AbortController can cancel a Fetch request. This helps prevent an older search from replacing newer results.

7. Important JavaScript Concepts Used Here

Fetch API

Fetch is the browser API for making network requests. It supports common HTTP methods such as GET, POST, PUT and DELETE.

Example 5: A simple GET request

async function loadProducts() {
  const response = await fetch(
    "https://dummyjson.com/products"
  );

  if (!response.ok) {
    throw new Error("Request failed");
  }

  const data = await response.json();
  console.log(data.products);
}

loadProducts();

Fetch does not reject its Promise for every HTTP error. Always check response.ok.

DOM Manipulation

DOM manipulation means changing page elements using JavaScript. We can create, update, remove and move elements.

Example 6: Create and add an element

const message = document.createElement("p");
message.textContent = "Products loaded successfully.";

document.body.append(message);

Expected output

Products loaded successfully.

Async and Await

async marks a function that returns a Promise. await waits for a Promise inside that function.

This keeps asynchronous code easier to read. It does not make the server respond instantly.

8. Common Mistakes and Best Practices

Mistake 1: Not checking the HTTP response

Wrong: Assuming every Fetch response means success.

const response = await fetch(url);
const data = await response.json();

Better: Check the status before reading the data.

const response = await fetch(url);

if (!response.ok) {
  throw new Error("Request failed");
}

const data = await response.json();

Rule: Check response.ok before using the response body.

Mistake 2: Using innerHTML with API data

Wrong: Adding untrusted API values directly through HTML strings.

productList.innerHTML =
  "<h2>" + product.title + "</h2>";

Untrusted values can contain unwanted HTML. This can create a cross-site scripting risk.

Better: Use textContent and createElement(). The main application uses this safer pattern.

Mistake 3: Forgetting loading and error states

Users need feedback while the request runs. Show loading, empty and error messages clearly.

Mistake 4: Sending a request for every keystroke

Fast typing can create many requests. Debouncing reduces unnecessary calls.

Mistake 5: Ignoring older requests

Network requests can finish in a different order. An older search could finish after a newer search. Use cancellation or request tracking.

Mistake 6: Forgetting URL encoding

Search terms can contain spaces and special characters. Use encodeURIComponent() when adding values to a URL.

9. Security and Production Considerations

  • Use HTTPS: Protect data while it travels across the network.
  • Validate on the server: Browser checks alone cannot protect server data.
  • Protect secrets: Never place private API keys inside browser JavaScript.
  • Handle CORS: The API server must allow requests from your website's origin.
  • Limit requests: Use sensible search delays and server-side rate limits.
  • Handle timeouts: Production applications should define suitable request time limits.
  • Check response data: Do not assume every API response has the expected shape.
  • Use pagination: Large catalogues should not load every record at once.

Security reminder: CORS is controlled by the server. It is not a replacement for authentication or authorization. Never trust browser-side checks to protect private data.

Local Learning Versus Production

What changes when the application goes live?
Learning application Production application
Public sample API. Managed business API.
Basic error messages. Central error reporting and useful user messages.
Simple search field. Search validation, pagination and filtering.
No user authentication. Authentication and authorization where needed.
Basic request handling. Timeouts, retries and monitoring where appropriate.

10. How This Topic Appears in Interviews

Question 1: How do you fetch API data in JavaScript?

What the interviewer wants: They want to understand your request and response handling.

Strong answer:

"I use the Fetch API to send an HTTP request. I check the response status before reading its body. Then I convert the response into JSON. I use the data to update the DOM. I also handle loading and error states."

Question 2: What is the difference between the DOM and an API?

Strong answer:

"The DOM represents the page inside the browser. An API allows applications to exchange data. In my shop example, the API provides product details. JavaScript uses the DOM to display those products."

Question 3: Why do you use async and await?

Strong answer:

"An API request takes time to finish. Async and await help us write asynchronous code clearly. The browser can continue handling other work while the request is pending. I also use try and catch to handle errors."

Question 4: How do you prevent unnecessary API calls?

Strong answer:

"I use debounce for search input. It waits until typing stops before sending a request. I can also cancel an older request using AbortController. This helps the page show the latest search results."

Senior and Architect-Level Follow-Ups

  • How would you add pagination to a large product catalogue?
  • How would you handle API retries and request timeouts?
  • How would you protect private API credentials?
  • How would you monitor API failures in production?
  • How would you prevent stale data from appearing?

11. Hands-On Practice

Beginner: Add Product Ratings

Show the product rating inside every card.

Hint: Create another paragraph. Set its text using product.rating.

Expected result: Every product card shows its rating.

Intermediate: Add a Category Filter

Add a category dropdown to the application. Show products from the selected category.

Hint: Explore the DummyJSON category endpoints. Keep the selected category in a JavaScript variable.

Expected result: Changing the category updates the displayed products.

Advanced: Add Pagination

Show a limited number of products on each page. Add Previous and Next buttons.

Hint: Explore the API's limit and skip query parameters.

Expected result: Users can move through product pages without loading the full catalogue.

Architect Challenge: Improve Request Reliability

Extend the application with request timeout handling. Add a retry option for temporary network failures. Prevent old responses from replacing new search results.

Expected result: The application handles slow requests and network failures more clearly.

12. Next Steps and Further Learning

Try these improvements after completing the application:

  • Explore HTTP methods such as GET, POST, PUT and DELETE.
  • Learn how HTTP status codes describe request results.
  • Understand Promises, async and await in more depth.
  • Explore browser storage for saved search preferences.
  • Learn pagination, caching and API authentication.
  • Build a small dashboard using a public API.

Official Documentation

Share Your Knowledge

Build your own version of this product search application. Try another public API and compare the results. Share your implementation and discuss improvements with other learners.

Learn Technology. Build Your Future.

Upgradix by Shrash Studio — Quality Technology Education. Completely Free.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.