Bent HTTP Client

7.3.12 · active · verified Wed Apr 22

Bent is a small, functional, and async/await-based HTTP client designed for both Node.js and browsers. Currently stable at version 7.3.12, it provides a fluent API for making HTTP requests with a focus on type-driven configuration. Key differentiators include its remarkably small bundle size (especially for browsers, where it's built on `fetch` with no external dependencies), flexible option parsing (inferring method, format, status codes, and base URL from argument types), and explicit error handling for unacceptable response statuses. While mature, its release cadence is not high, indicating stability over rapid feature churn. It differs from alternatives by prioritizing a functional, curried API over object-oriented design and by requiring explicit declaration of accepted status codes, which helps prevent unexpected success conditions.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating different `bent` instances for GET (JSON) and POST (JSON) requests, and fetching binary data as a buffer, with error handling.

const bent = require('bent');

async function fetchData() {
  try {
    // Create a bent instance for GET requests expecting JSON and 200 OK
    const getJSON = bent('GET', 'json', 200);
    // Create a bent instance for POST requests expecting 201 Created and JSON input/output
    const postJSON = bent('POST', 'json', 201);

    console.log('Fetching public JSON data...');
    const publicData = await getJSON('https://jsonplaceholder.typicode.com/todos/1');
    console.log('Public Data:', publicData);

    console.log('\nPosting new data...');
    const newData = { title: 'foo', body: 'bar', userId: 1 };
    // Using a fake API endpoint that always returns 201 for POST
    const postResponse = await postJSON('https://jsonplaceholder.typicode.com/posts', newData);
    console.log('Post Response:', postResponse);

    // Example of fetching a buffer (e.g., an image, though this is a text file)
    const getBuffer = bent('GET', 'buffer', 200);
    console.log('\nFetching a text file as buffer...');
    const buffer = await getBuffer('https://jsonplaceholder.typicode.com/todos/1'); // Fetching same data but as buffer
    console.log('Buffer content start:', buffer.toString().substring(0, 50), '...');

  } catch (error) {
    console.error('An error occurred:', error.message);
    if (error.statusCode) {
      console.error('Status Code:', error.statusCode);
    }
    if (error.text) {
        const errorBody = await error.text();
        console.error('Error Body:', errorBody);
    }
  }
}

fetchData();

view raw JSON →