Rests API Client SDK Generator

1.1.1 · active · verified Tue Apr 21

Rests is a JavaScript/TypeScript library designed to streamline and centralize HTTP API requests by enabling the generation of a structured API client SDK. It empowers developers to define API endpoints, methods, and parameters in a declarative, JSON-like configuration, thereby establishing a single source of truth for all API interactions. Key features include a robust configuration system that facilitates advanced handling of validation, authentication, and request/response hooks, alongside a powerful mechanism for complex inheritance that allows for the categorization of requests to prevent repetition. A significant differentiator is its capability to automatically generate TypeScript types for the defined API, enhancing developer experience and ensuring type safety. Additionally, it supports schema definition from pure JSON and can generate basic markdown API references. Rests offers universal compatibility, functioning seamlessly across both browser and Node.js environments. The current stable version is 1.1.1. While a specific release cadence is not explicitly detailed, the project appears to be under active development, evidenced by mentions of a 'Private edition' offering expanded functionalities. Its primary distinction lies in transforming a simple, declarative API definition into a fully-fledged, strongly-typed, and object-oriented API client, significantly simplifying network communication compared to direct `fetch` or `axios` implementations.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to define an API schema using the `Rests` factory, initialize the client, make successful and error-prone API calls, handle custom parameter validation, and set category-specific options like authorization.

import Rests from 'rests';

// Define your API schema with endpoints, methods, and validation rules
const APIBuilder = Rests({
  $options: {
    base: 'https://api.example.com' // Set the base URL for all requests
  },
  user: {
    login: {
      path: '/user/login',
      method: 'POST',
      params: {
        username: {
          required: true,
          type: "string",
          help: "A valid username is required",
          validate: /^[a-zA-Z0-9_]+$/ // Example validation for alphanumeric username
        },
        password: {
          required: true,
          help: "A valid password is required",
          type: "string",
          format: (password: string) => {
            if (password.length < 8) {
              throw new Error("The password must be at least 8 characters.");
            }
            return password;
          }
        }
      }
    },
    profile: {
      $options: {
        // Set authentication parameters for all requests in this category
        params: {
          authorization: { type: "string", required: true } 
        }
      },
      info: {
        path: '/user/profile/info',
        method: 'GET'
      },
      update: {
        path: '/user/profile/update',
        method: 'POST',
        params: {
          email: { type: "string", format: (email: string) => email.toLowerCase() }
        }
      }
    }
  }
});

// The API client is ready to use
const API = APIBuilder;

// Example 1: Successful login call
API.user.login({
    username: 'john.doe',
    password: 'supersecurepassword123'
})
.then((res) => {
    console.log('Login successful, response body:', res.json);
})
.catch((err) => {
    console.error('Login failed:', err.json || err.message);
});

// Example 2: Calling an endpoint with a validation error
API.user.login({
    username: 'testuser',
    password: 'short' // This will trigger the password format validation error
})
.catch((err) => {
    console.log('Validation Error:', err.field, err.message);
    // Expected output: "Validation Error: password The password must be at least 8 characters."
});

// Example 3: Initializing a category with specific options (e.g., authorization)
const UserAPI = new API.user({
  authorization: 'my_user_auth_token_xyz'
});

UserAPI.profile.info()
  .then((res) => console.log('User profile info retrieved:', res.json))
  .catch((err) => console.error('Failed to get user profile:', err.message));

view raw JSON →