Little API

raw JSON →
2.0.1 verified Thu Apr 23 auth: no javascript

`little-api` is a JavaScript library designed for creating simple JSON-over-HTTP/WS RPC servers and clients with minimal configuration. It acts as a lightweight wrapper around common web technologies like Express (for HTTP servers), XHRs (for HTTP clients), and WebSockets. The current stable version is 2.0.1. It provides a straightforward way to define server-side methods (both standard and WebSocket-specific) that are then exposed to a client-side API. A key differentiator is its emphasis on simplicity and low boilerplate, allowing developers to quickly set up RPC communication without diving into complex protocols. It strictly uses JSON as the transport format, meaning all arguments and return values must be JSON-serializable. Client-side usage relies on browser globals such as `XMLHttpRequest`, `WebSocket`, `btoa`, and `Promise`. The library does not specify a strict release cadence but provides a functional abstraction over underlying network primitives.

error TypeError: Converting circular structure to JSON
cause An argument passed from the client to the server, or a return value from the server to the client, contains a circular reference and cannot be serialized to JSON.
fix
Refactor your data structures to avoid circular references. If you need to pass complex objects, ensure they are simplified or transformed into JSON-serializable forms.
error ReferenceError: XMLHttpRequest is not defined
cause The `little-api` client is being used in an environment (e.g., Node.js) where `XMLHttpRequest` is not a global object.
fix
Ensure the client-side code runs in a browser environment or provide a suitable polyfill for XMLHttpRequest if running in a non-browser environment.
error Error: listen EADDRINUSE: address already in use :::8080
cause The port specified for the `little-api` server is already being used by another process.
fix
Change the port number for the little-api server or terminate the process currently using the desired port.
gotcha All data exchanged between client and server (arguments, return values) must be JSON-serializable. Complex types like functions, Dates, BigInts, or objects with circular references will not serialize correctly.
fix Ensure all data passed to and from API methods adheres to the JSON specification (strings, numbers, booleans, null, arrays, plain objects).
gotcha The client-side library (`little-api/client`) relies on browser global objects (`XMLHttpRequest`, `WebSocket`, `btoa`, `Promise`). It is not intended for Node.js client-side usage without polyfills for these globals.
fix Use `little-api/client` primarily in browser environments. If attempting to use in Node.js, ensure appropriate polyfills are available or consider a different RPC client solution.
deprecated The `.sync` property on client methods enables synchronous XHRs. Synchronous XHRs are largely deprecated in modern web development due to their blocking nature, which can freeze the browser UI and lead to a poor user experience.
fix Prefer the default asynchronous (Promise-based) client methods. Avoid `.sync` calls unless absolutely necessary for specific legacy contexts, and be aware of the performance implications.
npm install little-api
yarn add little-api
pnpm add little-api

This quickstart demonstrates setting up a `little-api` HTTP server with a few methods and then consuming those methods from a `little-api` client, including both asynchronous and synchronous calls.

const createServer = require("little-api/server");
const createClient = require("little-api/client");

const PORT = 8080;

// --- Server Setup ---
const server = createServer({
  methods: {
    uppercase(...words) {
      return words.map((word) => word.toUpperCase());
    },
    add(a, b) {
      return a + b;
    }
  },
});

server.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);

  // --- Client Usage (after server starts) ---
  const api = createClient({
    url: `http://localhost:${PORT}`,
    methods: ["uppercase", "add"],
  });

  api.uppercase("hello", "world").then((results) => {
    console.log("Uppercase results:", results); // Expected: ["HELLO", "WORLD"]
  }).catch(console.error);

  api.add(5, 3).then((result) => {
    console.log("Addition result:", result); // Expected: 8
  }).catch(console.error);

  // Example of synchronous call (use with caution in browser)
  try {
    const syncResults = api.uppercase.sync("sync", "test");
    console.log("Synchronous uppercase results:", syncResults); // Expected: ["SYNC", "TEST"]
  } catch (e) {
    console.warn("Synchronous XHR failed, likely not in browser or sync XHR disabled:", e.message);
  }

  // To gracefully shut down the server after a short period for this example
  setTimeout(() => {
    server.close(() => {
      console.log('Server closed.');
    });
  }, 2000);
});