rest.js HTTP Client

2.0.0 · active · verified Tue Apr 21

rest.js is an HTTP client library designed for both browser and Node.js environments, emphasizing extensibility through its interceptor-based architecture. It provides core functionality for making HTTP requests and normalizing request/response objects, with advanced features like MIME type conversion, error handling, and hypermedia API traversal implemented as composable interceptors. The current stable version is 2.0.0, which notably moved from a hard dependency on `when.js` to native ES6 Promises and completely dropped AMD module support. Releases historically occurred somewhat frequently for major feature additions in 1.x, with 2.0.0 being a significant breaking change. It allows developers to configure tailored HTTP clients by wrapping a basic client with only the necessary features, promoting a lightweight and modular approach to client-side HTTP interactions, differentiating it from monolithic HTTP libraries.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create an advanced `rest.js` client by composing multiple interceptors, including `pathPrefix` for base URL, `defaultRequest` for adding common headers, `mime` for automatic JSON parsing, and `errorCode` for robust error handling. It shows both GET and POST requests, using `process.env` for API key management.

const rest = require('rest');
const mime = require('rest/interceptor/mime');
const errorCode = require('rest/interceptor/errorCode');
const defaultRequest = require('rest/interceptor/defaultRequest');
const pathPrefix = require('rest/interceptor/pathPrefix');

// Assume a base URL and an API key for a hypothetical service
const API_BASE_URL = 'https://api.example.com';
const API_KEY = process.env.MY_API_KEY ?? 'your-secret-api-key'; // Use process.env for robustness

// Configure a client with common interceptors
// pathPrefix to handle base URL
// defaultRequest to add common headers like Authorization
// mime to automatically parse JSON responses
// errorCode to handle HTTP error statuses gracefully
const client = rest
    .wrap(pathPrefix, { prefix: API_BASE_URL })
    .wrap(defaultRequest, {
        headers: {
            'Authorization': `Bearer ${API_KEY}`,
            'Accept': 'application/json'
        }
    })
    .wrap(mime, { mime: 'application/json' })
    .wrap(errorCode, { code: 400 }); // Treat 400 and above as errors

// Make a request to fetch user data
client({ path: '/users/123' }).then(
    function(response) {
        console.log('User data:', response.entity);
        console.log('Status:', response.status.code);
    },
    function(error) {
        console.error('Request failed:', error.entity || error.message);
        console.error('Error status:', error.status && error.status.code);
    }
);

// Example of a POST request
client({
    path: '/users',
    method: 'POST',
    entity: { name: 'John Doe', email: 'john.doe@example.com' }
}).then(
    function(response) {
        console.log('New user created:', response.entity);
    },
    function(error) {
        console.error('Failed to create user:', error.entity || error.message);
    }
);

view raw JSON →