HTTP URL Builder

1.1.0 · active · verified Wed Apr 22

http-url-builder is a lightweight utility designed to simplify the construction of HTTP URLs, primarily for REST API interactions. It provides a fluent API to append path segments, add query parameters, and integrate path variables, streamlining the process of creating complex endpoints. The current stable version is 1.1.0, which notably introduced support for path variables. As a relatively new but actively maintained package, its release cadence is feature-driven, with updates focused on enhancing usability and functionality. Key differentiators include its explicit support for path variables, a clear and chainable API, and native TypeScript typings, which ensure a robust development experience compared to manual string concatenation or less specialized URL manipulation libraries.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate `URLBuilder`, add path segments, specify path variables, append query parameters, and finally build the complete URL string for various API endpoints, including proper URL encoding.

import { URLBuilder } from 'http-url-builder';

interface UserProfile { id: string; name: string; age: number; status: 'active' | 'inactive'; }

const API_BASE = 'https://api.example.com';

// Build a URL for fetching a user profile by ID
const userProfileUrl = new URLBuilder(API_BASE)
  .addPath('/users')
  .addPath('/{userId}')
  .withPathVariables({ userId: '123' })
  .addQuery('fields', 'id,name,status')
  .addQuery('expand', 'posts')
  .build();

console.log(`User Profile URL: ${userProfileUrl}`);
// Expected: https://api.example.com/users/123?fields=id,name,status&expand=posts

// Build a URL for searching users with specific criteria
const searchUsersUrl = new URLBuilder(API_BASE)
  .addPath('/search')
  .addQuery('query', 'john doe')
  .addQuery('limit', 10)
  .addQuery('page', 2)
  .build();

console.log(`Search Users URL: ${searchUsersUrl}`);
// Expected: https://api.example.com/search?query=john+doe&limit=10&page=2

// Example with optional parameters and encoding
const itemSearchUrl = new URLBuilder('https://store.example.com')
  .addPath('/items')
  .addQuery('category', 'electronics')
  .addQuery('q', 'usb-c adapter & charger') // Spaces and special chars handled
  .build();

console.log(`Item Search URL: ${itemSearchUrl}`);
// Expected: https://store.example.com/items?category=electronics&q=usb-c+adapter+%26+charger

view raw JSON →