Mohamed Reda Tech Logo
HomeArticlesApplicationsPhonesTutorialsTools
AR
Mohamed Reda Tech Logo
Mohamed Reda Tech

Tech articles, applications, and digital tools & services.

Follow Us
TelegramYouTube

Quick Links

ArticlesApplicationsTutorialsToolsPhones

Help

About UsAbout the authorEditorial policyContact Us

Stay Connected

Get notified when new articles, tools, and app updates are released.

© 2026 MR. All rights reserved.

Privacy Policy•Terms of Service•
Mastering REST APIs with JavaScript: Fetch, Async/Await, and JSON Handling · Mohamed Reda Tech
  1. Home
  2. Tutorials
  3. Mastering REST APIs with JavaScript: Fetch, Async/Await, and JSON Handling
Tutorials

Mastering REST APIs with JavaScript: Fetch, Async/Await, and JSON Handling

Learn client-server communication in modern JavaScript: GET requests, POST mutations, robust error handling with try/catch, and network timeouts with AbortController.

By Mohamed RedaPublished: October 15, 2026Updated: November 2, 20262 min read
HTTP Fetch Protocol Pipeline and JSON Packet Stream

The Communication Bridge of Modern Web Apps

Modern Single Page Applications (SPAs) do not reload the entire browser page to retrieve fresh data. Instead, client-side JavaScript issues non-blocking background HTTP requests via the Fetch API, exchanges serialized JSON payloads, and reacts dynamically to update the Document Object Model (DOM).

1. Fetching Data with Async/Await (GET Requests)

A robust implementation handles loading states, HTTP status validation, and error boundaries:

async function loadArticles() {
  const container = document.querySelector("#articles-list");
  
  try {
    // Surface immediate loading feedback
    container.innerHTML = "<p class='loading'>Fetching latest publications...</p>";

    const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5");
    
    // Explicitly validate HTTP status code (200-299)
    if (!response.ok) {
      throw new Error(`Server returned status: ${response.status} (${response.statusText})`);
    }

    // Parse JSON stream into typed JavaScript objects
    const articles = await response.json();

    // Render data securely into the DOM
    container.innerHTML = articles.map(article => `
      <div class="article-card">
        <h3>${article.title}</h3>
        <p>${article.body}</p>
      </div>
    `).join("");

  } catch (error) {
    console.error("Failed to fetch articles:", error);
    container.innerHTML = `<p class="error">Unable to reach service. Please verify your connection.</p>`;
  }
}

loadArticles();

2. Mutating Resources (POST Requests)

When publishing articles or submitting user credentials, dispatch a POST request configured with explicit headers and a JSON-serialized string body:

async function createNewArticle(articleData) {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
      method: "POST",
      headers: {
        "Content-Type": "application/json; charset=UTF-8",
        "Accept": "application/json",
      },
      body: JSON.stringify(articleData)
    });

    if (!response.ok) {
      throw new Error(`Mutation failed with status: ${response.status}`);
    }

    const createdRecord = await response.json();
    console.log("Resource successfully committed:", createdRecord);
    return createdRecord;

  } catch (error) {
    console.error("Network dispatch error:", error);
    alert("Submission failed. Please check network logs.");
  }
}

// Invoke mutation
createNewArticle({
  title: "Building Resilient Distributed Systems",
  body: "Architectural patterns for high availability and fault isolation.",
  userId: 1
});

3. Timeout Handling with AbortController

Prevent hanging requests on degraded connections by enforcing explicit timeout limits using AbortController:

async function fetchWithTimeout(url, timeoutMs = 8000) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);

  try {
    const response = await fetch(url, { signal: controller.signal });
    clearTimeout(timer);
    
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    return await response.json();
  } catch (err) {
    if (err.name === "AbortError") {
      throw new Error("Request timed out after " + timeoutMs + "ms");
    }
    throw err;
  }
}

Summary

Combining the Fetch API with Async/Await, strict HTTP status validation, and AbortController creates resilient network interaction layers essential for production-grade web applications.

Related articles

Tutorials

Google Find My Device guide: locate, lock, or erase your lost Android phone remotely

Lost or stolen phone? A practical guide to Google's Find My Device: what to set up before you lose it, how to locate, ring, lock, or erase it remotely, and the real limits of each option.

November 28, 20263 min read
Tutorials

Comments(0)

Leave a comment

Share your thoughts or questions. Your email will not be published.

No comments yet. Be the first to share your thoughts!

Frequently asked questions

Why does fetch() not reject promises on HTTP 404 or 500 status codes?+

The Fetch specification treats any received HTTP response as a resolved promise. Network errors or DNS failures reject the promise, but server status codes must be checked manually via response.ok or response.status.

What is the primary architectural advantage of Async/Await over raw Promises?+

Async/Await provides syntactic sugar that allows developers to write asynchronous logic with procedural readability and structured synchronous-style try/catch/finally error handling blocks.

How do you pass authentication tokens with fetch requests?+

Include an Authorization header in the request options object: headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' }.

Translate Chrome Pages on Android: Choose a Language and Manage Automatic Translation

Request page translation, choose its destination language and manage automatic or excluded languages. Learn how these differ from Chrome’s interface language.

November 28, 20264 min read
Tutorials

Chrome Reading Mode on Android: Adjust Text, Fonts and Background Colors

Open Reading mode for supported pages, adjust font style and size, and choose light, sepia or dark backgrounds. Understand unavailable pages and the difference from audio playback.

November 24, 20264 min read
Tutorials

Android Privacy Dashboard: Review Camera and Microphone Use and Change Permissions

Find permission activity, identify the app and access time, then change one permission and test the feature. Understand Android 12 and 13 history windows and the limits of the log.

November 24, 20264 min read