Typesafe API Call Utility

5.1.2 · active · verified Tue Apr 21

typesafe-api-call is a minimalistic JavaScript library designed to streamline API interactions by enforcing typesafety and a functional programming paradigm. It abstracts away traditional exception handling, instead ensuring that every API call resolves to an explicit `APISuccess` or `APIFailure` result, compelling developers to handle both successful and unsuccessful outcomes distinctly. The library is currently on version 5.1.2 and appears to have an active release cadence, with recent patches and new features like `callWithRetries` introduced in minor versions. A key differentiator is its emphasis on functional results over exceptions, promoting predictable state management. It also integrates seamlessly with complementary tools like `type-decoder` and `type-crafter` to facilitate YAML-driven type and decoder generation, further enhancing end-to-end typesafety for API responses.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates a basic GET API call using `APICaller`, showing how to define a request, provide decoding functions, and handle the explicit `APISuccess` or `APIFailure` result.

import { APICaller, APIResponse, type APIRequest, APISuccess } from 'typesafe-api-call';

interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

const serverEndpoint = 'https://jsonplaceholder.typicode.com';

async function getAllPosts(): Promise<APIResponse<Post[], unknown>> {
  const apiRequest: APIRequest = {
    url: new URL(`${serverEndpoint}/posts`),
    method: 'GET'
  };

  // Using an anonymous function for decoding. In a real app, you'd use a dedicated decoder.
  const apiResponse = await APICaller.call(
    apiRequest,
    (successResponse: unknown) => successResponse as Post[], // Simulate decoding
    (errorResponse: unknown) => errorResponse // Error handling can also include decoding
  );
  return apiResponse;
}

async function runExample() {
  console.log('Fetching all posts...');
  const getAllPostResult = await getAllPosts();

  if (getAllPostResult instanceof APISuccess) {
    console.log('Successfully fetched posts:', getAllPostResult.data.slice(0, 2));
  } else {
    console.log('Failed to fetch posts:', getAllPostResult.error);
  }
}

runExample();

view raw JSON →