How do you consume and call a REST API from client-side JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you consume and call a REST API from client-side JavaScript?

message-square
0

To consume and call a REST API from client-side JavaScript, use the browser fetch(url, options) API (with an AbortController signal for timeouts/cancellation and explicit HTTP method/headers/JSON.stringify body when sending data), validate the endpoint URL, HTTP options, response status (response.ok), and Map registries/caches using typeof / instanceof / Array.isArray checks, and wrap request execution and JSON parsing inside try / catch blocks so network errors, non-2xx HTTP responses, and malformed JSON payloads fail deterministically.


1. Making a Validated fetch() Request with Timeout (AbortController) and try / catch

Validate the target URL, HTTP method, and timeout before calling fetch(), check response.ok explicitly (since fetch() does not reject on HTTP 4xx/5xx status codes), and parse JSON safely inside try / catch:

// Execute a validated client-side REST API request using fetch() and AbortController
async function requestRestApi(endpointUrl, {
  method = "GET",
  headers = {},
  body = undefined,
  timeoutMs = 8000
} = {}) {
  if (typeof endpointUrl !== "string" || endpointUrl.trim().length === 0) {
    throw new TypeError("Expected endpointUrl to be a non-empty string.");
  }
  if (typeof method !== "string" || method.trim().length === 0) {
    throw new TypeError("Expected method to be a non-empty string.");
  }
  if (typeof headers !== "object" || headers === null || Array.isArray(headers)) {
    throw new TypeError("Expected headers to be a non-null plain/record object.");
  }
  if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
    throw new RangeError("Expected timeoutMs to be a positive finite number.");
  }
  if (typeof fetch !== "function" || typeof AbortController !== "function") {
    throw new Error("Browser fetch() and AbortController APIs are required.");
  }

  const normalizedMethod = method.trim().toUpperCase();
  const abortController = new AbortController();
  const timeoutId = setTimeout(() => {
    try {
      abortController.abort(new Error(`Request timed out after ${timeoutMs}ms.`));
    } catch (abortError) {
      const msg = abortError instanceof Error ? abortError.message : String(abortError);
      console.error(`Failed aborting timed-out request: ${msg}`);
    }
  }, timeoutMs);

  try {
    const requestHeaders = new Map([
      ["Accept", "application/json"]
    ]);

    for (const [headerKey, headerVal] of Object.entries(headers)) {
      if (typeof headerKey === "string" && headerKey.trim().length > 0 && typeof headerVal === "string") {
        requestHeaders.set(headerKey.trim(), headerVal);
      }
    }

    const fetchOptions = {
      method: normalizedMethod,
      signal: abortController.signal
    };

    if (body !== undefined && normalizedMethod !== "GET" && normalizedMethod !== "HEAD") {
      requestHeaders.set("Content-Type", "application/json");
      fetchOptions.body = typeof body === "string" ? body : JSON.stringify(body);
    }

    const plainHeaders = {};
    for (const [k, v] of requestHeaders.entries()) {
      plainHeaders[k] = v;
    }
    fetchOptions.headers = plainHeaders;

    const response = await fetch(endpointUrl.trim(), fetchOptions);

    if (!(response instanceof Response)) {
      throw new Error("Expected fetch() to resolve to a Response instance.");
    }

    const rawText = await response.text();
    let parsedPayload = null;

    if (rawText.trim().length > 0) {
      try {
        parsedPayload = JSON.parse(rawText);
      } catch (jsonError) {
        const jsonMsg = jsonError instanceof Error ? jsonError.message : String(jsonError);
        throw new SyntaxError(`Invalid JSON response from REST API: ${jsonMsg}`);
      }
    }

    if (!response.ok) {
      throw new Error(
        `REST API request failed with HTTP ${response.status} (${response.statusText || "Error"}).`
      );
    }

    return new Map([
      ["ok", true],
      ["status", response.status],
      ["data", parsedPayload]
    ]);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed consuming REST API "${endpointUrl}": ${message}`);
  } finally {
    clearTimeout(timeoutId);
  }
}

// Example usage:
// try {
//   const resultMap = await requestRestApi("https://api.example.com/v1/items", {
//     method: "POST",
//     headers: { Authorization: "Bearer <token>" },
//     body: { title: "New Reference Entry" }
//   });
//   console.log("API status:", resultMap.get("status"), "Data:", resultMap.get("data"));
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Always check response.ok (status 200-299): fetch() resolves on 404 or 500 responses unless you throw on !response.ok.
  • Always clear timeoutId in finally: Prevents leaked timers once a request finishes or fails early.

2. Caching and Tracking REST Endpoints with a Map

When calling multiple REST endpoints or deduplicating/caching responses by endpoint key in client code, store entries in a Map so dynamic URLs or resource keys never collide with Object.prototype properties:

// Fetch and cache a REST GET response in a Map registry with validation and try / catch
async function fetchAndCacheRestResource(cacheMap, cacheKey, endpointUrl, requestOptions = {}) {
  if (!(cacheMap instanceof Map)) {
    throw new TypeError("Expected cacheMap to be a Map instance.");
  }
  if (typeof cacheKey !== "string" || cacheKey.trim().length === 0) {
    throw new TypeError("Expected cacheKey to be a non-empty string.");
  }
  if (typeof endpointUrl !== "string" || endpointUrl.trim().length === 0) {
    throw new TypeError("Expected endpointUrl to be a non-empty string.");
  }

  try {
    const cleanKey = cacheKey.trim();
    if (cacheMap.has(cleanKey)) {
      return cacheMap.get(cleanKey);
    }

    const apiResultMap = await requestRestApi(endpointUrl, {
      ...requestOptions,
      method: "GET"
    });

    const payload = apiResultMap.get("data");
    cacheMap.set(cleanKey, payload);
    return payload;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed fetching/caching resource "${cacheKey}": ${message}`);
  }
}

// Example usage:
// try {
//   const resourceCache = new Map();
//   const users = await fetchAndCacheRestResource(
//     resourceCache,
//     "users:page=1",
//     "https://api.example.com/v1/users?page=1"
//   );
//   console.log("Cached users count:", Array.isArray(users) ? users.length : 0);
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Use Map rather than {} for endpoint/query cache keys: URLs and query strings contain characters and names that are much safer and cleaner in a Map.
  • Avoid embedding long-lived secrets/API keys directly in client-side JavaScript: Browser bundle code is public; authenticate users via short-lived tokens or backend session cookies over HTTPS.

3. CORS, Auth Headers, and Error Handling Caveats

Keep these browser REST client realities in mind in production applications:

  • Cross-Origin Resource Sharing (CORS) is enforced by the browser and server: If the API origin differs from your page origin, the server must send appropriate Access-Control-Allow-Origin (and preflight Access-Control-Allow-Methods / Access-Control-Allow-Headers) headers.
  • Avoid sending a request body on GET or HEAD requests: Browsers reject fetch() calls that attach a body to GET or HEAD—pass query parameters on the URL (new URLSearchParams(...)) instead.
  • Handle 204 No Content and non-JSON responses gracefully: Reading response.text() before JSON.parse() prevents SyntaxError on empty 204 responses.