purest REST API Client Library

repository·master·Indexed 20 days ago

https://github.com/simov/purest

An expressive REST API client library (version 4.0.3) designed to abstract API complexities through flexible configuration and endpoint mapping. It features dynamic URL construction using tokens, support for provider-based configurations, method aliasing, and specialized handling for OAuth and multipart requests. The library provides multiple response methods including request(), buffer(), and stream(), and supports automatic parsing of JSON and querystring bodies.

Tokens
2.8K
Snippets
9
Records
13
Agent score
69%

What's inside purest

  1. Configure Providers and Endpoints

    master

    Purest uses a configuration object to map providers to base URLs and paths. You can define a default endpoint for a provider or explicit endpoints for specific sub-services.

    Default Endpoint

    The default key defines the base configuration for the provider. Use tokens like {path} in the path field to allow appending sub-paths.

    Explicit Endpoint

    You can define specific endpoints (e.g., youtube inside a google provider) with their own origin, path, and tokens like {version} or {path}. This allows you to call the endpoint by name.

    Example configuration:

    {
      "google": {
        "default": {
          "origin": "https://www.googleapis.com",
          "path": "{path}",
          "headers": { "authorization": "Bearer {auth}" }
        },
        "youtube": {
          "origin": "https://www.googleapis.com",
          "path": "youtube/{version}/{path}",
          "version": "v3",
          "headers": { "authorization": "Bearer {auth}" }
        }
      }
    }
  2. Initialize Purest with a Provider

    master

    To use Purest, initialize it by passing an options object. You can specify a provider to select a pre-configured set of endpoints from your config, or provide a custom config object to define your own API structures.

    Basic initialization pattern:

    var purest = require('purest')
    var google = purest({provider: 'google', config: myConfig})
    var purest = require('purest')
    var google = purest({provider: 'google'})
  3. Set Default Request Values

    master

    You can preconfigure every method in a Purest instance using the defaults option. This is useful for values like authentication tokens that are required for every request.

    var google = purest({
      provider: 'google', 
      config, 
      defaults: { auth: token }
    })
    
    // Now you don't need to call .auth(token) manually
    await google('youtube').get('channels').request()
    var google = purest({provider: 'google', config, 
      defaults: {auth: token}
    })
  4. Create Method Aliases

    master

    You can define custom aliases for Purest methods using the methods option. This allows you to use more expressive names (e.g., using select instead of get).

    var google = purest({
      provider: 'google', 
      config, 
      defaults: { auth: token },
      methods: { get: ['select'], qs: ['where'] }
    })
    
    // Usage with aliases
    await google('youtube')
      .select('channels')
      .where({ forUsername: 'GitHub' })
      .request()
    var google = purest({provider: 'google', config, 
      defaults: {auth: token}, 
      methods: {get: ['select'], qs: ['where']}
    })
  5. Use method aliases and chaining for configuration

    master

    The Purest client automatically exposes all defined methods and their aliases as properties on the client object. These methods can be used to set configuration options before executing a request.

    Authentication

    Methods related to auth (including aliases) allow you to set authentication credentials. Calling an auth method returns the client instance to allow further chaining.

    Request Execution

    Methods like request, buffer, and stream (and their aliases) are used to execute the request. When these are called, they trigger the request execution using the accumulated options.

    General Options

    Other methods set specific keys in the request options object and return the client for chaining.

    const client = purest();
    
    // Chaining auth and then executing a request via a method alias
    client
      .auth('Bearer my-token')
      .get('/api/resource') // assuming 'get' is an alias for 'request' with method: 'GET'
      .then(res => console.log(res));
  6. Construct URLs using Purest URL logic

    master

    When providing options to Purest, the URL can be constructed automatically using template placeholders. If a url property is already present in the options object, it is used as-is. Otherwise, Purest attempts to build a URL by combining origin and path, replacing specific placeholders within the path string.

    Supported placeholders in the path string:

    • {path}: Replaced by the value of the HTTP method key (e.g., if options.get is provided, {path} becomes the value of options.get). If no method key is found, it defaults to an empty string.
    • {subdomain}: Replaced by options.subdomain.
    • {version}: Replaced by options.version.
    • {type}: Replaced by options.type.

    If the value associated with the detected HTTP method starts with http or https, it is assigned directly to options.url.

    // Example of template replacement logic
    const options = {
      origin: 'https://api.{subdomain}.com/{version}',
      path: '/{type}/{path}',
      subdomain: 'example',
      version: 'v1',
      type: 'users',
      get: 'profile'
    };
    
    // Resulting URL would be: https://api.example.com/v1/users/profile
  7. Perform HTTP Requests with Request Options

    master

    Purest provides several ways to execute requests. You can use HTTP method shorthand (e.g., .get(), .post()) or the generic .request() method.

    Response Methods

    • request(): Buffers the response, decompresses gzip/deflate, converts to string (UTF-8), and attempts to parse JSON or querystring. Returns String or Object.
    • buffer(): Buffers the response and decompresses gzip/deflate. Returns a Buffer.
    • stream(): Returns the response as a Stream.

    Common Request Options

    OptionTypeDescription
    methodstringRequest method (implicitly set if using HTTP method shorthands)
    urlstring / URLAbsolute URL. Overrides URL construction from config.
    qsobject / stringURL querystring
    headersobjectRequest headers
    formobject / stringapplication/x-www-form-urlencoded body
    jsonobject / stringJSON encoded request body
    multipartobject / arraymultipart/form-data or multipart/related body
    bodystring / Buffer / StreamRaw request body
    authstring / [string, string]Replaces {auth} token or provides Basic auth
    oauthobjectOAuth 1.0a authorization
    timeoutnumberRequest timeout in milliseconds
  8. Use Purest Options for Initialization

    master

    When calling purest(), you can pass the following options:

    KeyTypeDescription
    providerstringProvider name to initialize from the list of providers found in config
    configobjectProviders configuration to use
    defaultsobjectAny supported configuration option set by default (e.g., auth)
    methodsobjectList of methods and their aliases to use with this instance
    var google = purest({config: {}, provider: 'google', defaults: {}, methods: {}})
  9. Access Explicit Endpoints

    master

    If you have defined explicit endpoints in your configuration, you can access them using several patterns:

    // 1. As an argument to the Purest instance
    await google('youtube').get('channels').request()
    
    // 2. Using the .endpoint() method
    await google.endpoint('youtube').get('channels').request()
    
    // 3. Using a default method alias (if configured)
    await google.query('youtube').get('channels').request()
  10. Configure URL and Path Tokens

    master

    Purest allows dynamic URL construction using tokens in the origin and path configuration fields:

    OptionDescription
    originThe protocol and domain part of the URL. Can contain {subdomain} token.
    pathThe path part of the URL. Can contain {version}, {path}, and {type} tokens.
    subdomainSubdomain part of the URL to replace in origin.
    versionVersion string to replace in path.
    typeType string to replace in path (typically json or xml).
  11. Instantiate a Purest client

    master

    To use Purest, call the exported function with an optional configuration object (ctor). The returned client is a function that can be invoked with request options or used to chain configuration.

    If you call the client without arguments, it returns itself. If you pass a string, it sets the endpoint for the client. If you pass an object, it executes a request using those options.

    Common patterns include:

    • Setting an endpoint: client('https://api.example.com')
    • Executing a request: client({ method: 'GET', url: '/users' })
    • Chaining configuration: client.auth('token').get('/data')
    const purest = require('purest');
    
    // Create a client with custom configuration
    const client = purest({
      methods: {
        // custom method aliases if needed
      }
    });
    
    // Set endpoint and execute a request
    client('https://api.example.com')({ method: 'GET', url: '/path' })
      .then(response => console.log(response));
  12. Initialize the Purest client

    master

    The Purest client is created by requiring the module, which returns an extended request-compose instance. This client provides specialized handling for OAuth, multipart requests, and automatic response parsing based on the Content-Type header.

    To use it, simply require the package. The client is pre-configured with:

    • Request capabilities: Supports oauth and multipart via the Request property.
    • Response capabilities: Includes a parse method in the Response property that automatically detects and parses application/json, application/javascript, and application/x-www-form-urlencoded bodies.
    • Debugging: If the DEBUG environment variable is set, the client attempts to use request-logs to log request/response data.
    const purest = require('purest');
    
    // The exported object is an extended request-compose instance
    // with Request and Response capabilities.