npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

call-api-fh

v3.0.24

Published

A robust js utility for making API calls with error handling, timeout support, and debugging options

Readme

callAPI

A robust, feature-rich js utility for making API calls with support for error handling, request timeout, license validation, and debugging.

Features

  • ✅ TypeScript support with comprehensive type definitions
  • ✅ Built-in error handling and custom error classes
  • ✅ Request timeout support
  • ✅ Optional license validation
  • ✅ Detailed debugging options
  • ✅ Flexible response handling

Installation

npm i call-api-fh

Basic Usage

import { callApi } from "call-api";

// Simple GET request
const fetchData = async () => {
  try {
    const response = await callApi({
      baseUrl: "https://api.example.com",
      path: "/users",
      method: "GET",
      queryParams: { page: 1, limit: 10 },
    });

    console.log(response);
  } catch (error) {
    console.error("Failed to fetch data:", error);
  }
};

API Reference

callApi(params: ApiCallOptions): Promise<any>

The main function to make API calls with various options.

Parameters

params - An object with the following properties:

| Property | Type | Required | Default | Description | | ------------------ | ---------------------------------------------------------------- | -------- | --------- | ---------------------------------------- | | baseUrl | string | Yes | - | The base URL for API calls | | path | string | Yes | - | The path to append to the base URL | | method | HttpMethod | No | 'GET' | HTTP method to use | | headers | Record<string, string> | No | {} | HTTP headers to include | | body | unknown | No | undefined | Request body (automatically stringified) | | queryParams | Record<string, string | number | boolean | null | undefined> | No | undefined | Query parameters to append to the URL | | skipURIEncoding | boolean | No | false | Skip URI encoding of query parameters | | debug | DebugOptions | No | {} | Debug options (see below) | | responseHandlers | ResponseHandlers | No | {} | Success and error handlers | | validateLicense | CommonApiParams & ResponseHandlers | No | undefined | License validation options | | timeout | number | No | 10000 | Request timeout in milliseconds |

Debug Options

| Property | Type | Default | Description | | ------------- | ------- | ------- | ------------------------------- | | logUrl | boolean | false | Log the constructed URL | | logRequest | boolean | false | Log the request body | | logResponse | boolean | false | Log the raw response | | logData | boolean | false | Log the processed response data |

Response Handlers

| Property | Type | Description | | ----------- | --------------------------- | --------------------------------- | | onSuccess | (response: unknown) => void | Called on successful API response | | onError | (error: unknown) => void | Called when an error occurs |

Error Classes

ApiResponseError

Thrown when the API returns an error status code.

class ApiResponseError extends Error {
  statusCode: number;
  response?: unknown;
}

NetworkError

Thrown when a network-related error occurs.

class NetworkError extends Error {}

TimeoutError

Thrown when a request exceeds the timeout duration.

class TimeoutError extends Error {}

Advanced Examples

POST Request with Request Body

const createUser = async (userData) => {
  try {
    const response = await callApi({
      baseUrl: "https://api.example.com",
      path: "/users",
      method: "POST",
      body: userData,
      headers: {
        Authorization: "Bearer token123",
      },
    });

    return response;
  } catch (error) {
    console.error("Failed to create user:", error);
    throw error;
  }
};

With License Validation

const fetchProtectedData = async () => {
  try {
    const response = await callApi({
      baseUrl: "https://api.example.com",
      path: "/protected-data",
      validateLicense: {
        path: "/validate-license",
        body: { licenseKey: "YOUR_LICENSE_KEY" },
        onError: (error) => console.error("License validation failed:", error),
      },
    });

    return response;
  } catch (error) {
    console.error("Failed to fetch protected data:", error);
    throw error;
  }
};

With Debug Options

const debugApiCall = async () => {
  try {
    const response = await callApi({
      baseUrl: "https://api.example.com",
      path: "/debug-endpoint",
      debug: {
        logUrl: true,
        logRequest: true,
        logResponse: true,
        logData: true,
      },
    });

    return response;
  } catch (error) {
    console.error("Debug API call failed:", error);
    throw error;
  }
};

Using Response Handlers

const handleApiCall = async () => {
  await callApi({
    baseUrl: "https://api.example.com",
    path: "/data",
    responseHandlers: {
      onSuccess: (data) => {
        console.log("Success:", data);
        // Process data further
      },
      onError: (error) => {
        console.error("Error occurred:", error);
        // Handle error, show notification, etc.
      },
    },
  });
};

License

MIT