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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@electi/typescript-rest-api-fetcher

v2025.11.14-1020

Published

Welcome to the comprehensive documentation for the **Type-Safe REST API Fetching Library**. This package is designed to make REST API calls type-safe and highly configurable. The primary goal is to ensure that your API requests are consistent, predictable

Readme

Type-Safe REST API Fetching Library

Welcome to the comprehensive documentation for the Type-Safe REST API Fetching Library. This package is designed to make REST API calls type-safe and highly configurable. The primary goal is to ensure that your API requests are consistent, predictable, and fully typed, reducing the chances of runtime errors and enhancing the developer experience.

Key Features

  • Type Safety: Ensures that all API requests and responses are typed, providing a safeguard against runtime errors.
  • Configurable Mock Responses: Enables easy switching between real and mock API responses, facilitating testing and development without reliance on the actual backend.
  • Detailed HTTP Status Handling: Robust error handling through detailed HTTP status codes, reducing the complexity of managing various server responses.

Installation

To get started with this package, simply install it via npm or yarn:

npm install @electi/typescript-rest-api-fetcher
# or
yarn add @electi/typescript-rest-api-fetcher

Usage Overview

The library revolves around a few key classes and functions that help define and handle API requests. Below is a detailed explanation of these components.

DefaultRequestHeader Class

The DefaultRequestHeader class encapsulates all standard HTTP request headers. This class can be extended or used as-is to define headers for your API requests.

Example:

import { DefaultRequestHeader } from '@electi/typescript-rest-api-fetcher';

class MyRequestHeaders extends DefaultRequestHeader {
  constructor() {
    super();
    this.authorization = 'Bearer my-token';
    this.accept = 'application/json';
  }
}

HttpMethod Enum

The HttpMethod enum provides the standard HTTP methods for API requests. This ensures that only valid HTTP methods are used.

  • GET
  • POST
  • PUT
  • DELETE

Example:

import { HttpMethod } from '@electi/typescript-rest-api-fetcher';

const method: HttpMethod = HttpMethod.POST;

HttpStatus Class

The HttpStatus class is a powerful utility for handling HTTP status codes. It categorizes responses into informational, successful, redirection, client errors, and server errors. This makes it easier to interpret and handle responses appropriately.

Example:

import { HttpStatus } from '@electi/typescript-rest-api-fetcher';

if (response.status === HttpStatus.OK.value) {
  console.log('Request was successful!');
}

MockApiResponse Class

The MockApiResponse class is used to define mock responses for your API endpoints. This is particularly useful for testing and development, allowing you to simulate server responses without hitting a real API.

Example:

import { MockApiResponse, HttpStatus } from '@electi/typescript-rest-api-fetcher';

const mockResponse = MockApiResponse.createMockApiResponse(
  { data: 'mock data' },
  HttpStatus.OK,
  100, // 100ms query duration
  false // offline status
);

RestApiDefinition Class

The RestApiDefinition class allows you to define the structure of your API endpoints. This includes the method, path, expected statuses, and mock responses. It serves as the blueprint for each API request, ensuring consistency across your application.

Example:

import { RestApiDefinition, HttpMethod, HttpStatus, MockApiResponse } from '@electi/typescript-rest-api-fetcher';

const myApi = new RestApiDefinition(
  'GetUserData',
  HttpMethod.GET,
  '/user/data',
  [HttpStatus.OK],
  MockApiResponse.createMockApiResponse({ user: 'John Doe' }, HttpStatus.OK),
  true // Activate mock response
);

handleRequest Function

The handleRequest function is the core of the library, where all API calls are made. It takes in a RestApiDefinition, along with request parameters, body, and headers, and returns a promise that resolves with the typed response.

Example:

import { handleRequest, RestApiDefinition, DefaultRequestHeader, HttpMethod, HttpStatus } from '@electi/typescript-rest-api-fetcherh';

const getUserData = new RestApiDefinition(
  'GetUserData',
  HttpMethod.GET,
  '/user/data',
  HttpStatus.OK,
  MockApiResponse.createMockApiResponse({ user: 'John Doe' }, HttpStatus.OK)
);

const requestParams = {};
const requestBody = null;
const requestHeaders = new DefaultRequestHeader();

handleRequest(getUserData, requestParams, requestBody, requestHeaders)
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.error('Error fetching user data:', error);
  });

Error Handling

The library provides robust error handling via the RestClientErrorException class. It allows you to catch and handle different types of errors such as client errors, server errors, unexpected success responses, and network issues.

Example:

import { handleRequest, RestClientErrorException, RestApiDefinition, DefaultRequestHeader, HttpMethod, HttpStatus } from '@electi/typescript-rest-api-fetcher';

try {
  const response = await handleRequest(getUserData, requestParams, requestBody, requestHeaders);
  console.log(response);
} catch (error) {
  if (error instanceof RestClientErrorException) {
    console.error('An error occurred:', error.message);
    // Handle specific error cases based on error.errorType
  } else {
    console.error('Unknown error:', error);
  }
}

RestClientErrorException Class

The RestClientErrorException class provides a structured way to deal with errors. It encapsulates the error type, HTTP status, and any additional information returned by the server.

Error Types:

  • SERVER_ERROR: Indicates an issue on the server side.
  • CLIENT_ERROR: Indicates a problem with the request made by the client.
  • UNEXPECTED_SUCCESS_ERROR: Occurs when an unexpected success status code is returned.
  • NETWORK_ERROR: Triggered when there is a network issue during the API call.
  • INTERNAL_ERROR: Catch-all for any other unexpected issues.

Advanced Configuration

RestApiFetchConfig

This configuration object allows you to set global settings for your API requests, such as the API host, base path, and whether to use mock responses globally.

import { CONFIG } from '@electi/typescript-rest-api-fetcher';

CONFIG.API_HOST = 'https://api.example.com';
CONFIG.API_BASE_PATH = '/v1';
CONFIG.USE_MOCK_API_FOR_ALL_REQUESTS = true;

Conclusion

This library is designed to simplify and streamline the process of making API requests in a type-safe manner. By leveraging the power of TypeScript, it ensures that your API interactions are reliable, predictable, and easy to maintain. Whether you’re building a small app or a large-scale enterprise solution, this package provides the tools you need to manage your API requests effectively.

Happy coding! 🎉