An open API service indexing awesome lists of open source software.

https://github.com/santiagovogit/http-client-for-ts

A HTTP client for making requests inspired by the design of the Java HTTP client
https://github.com/santiagovogit/http-client-for-ts

api fetch fetch-api http http-client http-requests java request typescript typescript-library

Last synced: 8 months ago
JSON representation

A HTTP client for making requests inspired by the design of the Java HTTP client

Awesome Lists containing this project

README

          

# http-client-for-ts

[![npm version](https://badge.fury.io/js/http-client-for-ts.svg)](https://badge.fury.io/js/http-client-for-ts)[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
[![Node.js](https://img.shields.io/badge/Node.js-18%2B-green.svg)](https://nodejs.org/)
[![ESM](https://img.shields.io/badge/ESM-Native-purple.svg)]()

Modern TypeScript HTTP client with a fluent API inspired by Java's HttpClient,
providing an elegant abstraction layer over the Fetch API.

## Features

- 📦 **Zero Dependencies**: Lightweight ESM-native with minimal bundle impact
- 📝 **Type Safety**: Full TypeScript support with generic responses
- 🏗️ **Builder Pattern**: Fluent API for configuring clients and requests
- 🔄 **Auto Serialization**: Built-in serialization/deserialization for request and response bodies
- ⏱️ **Timeout Support**: Built-in request cancellation and timeout handling
- 🔒 **Immutable Objects**: Thread-safe request/response handling
- ⚡ **Fetch API Based**: High performance through native browser/Node.js APIs
- 🔍 **Smart Error Handling**: Dedicated exception types for different scenarios

## Why Choose http-client-for-ts?

### 🎯 **Java-Inspired Design**

Familiar builder pattern for enterprise developers transitioning from Java ecosystem.

### 🛡️ **Type Safety First**

Built from the ground up with TypeScript, not retrofitted onto JavaScript.

### ⚡ **Modern & Lightweight**

- ESM-only for optimal tree-shaking
- Promise-based, modern async interface
- Zero dependencies
- Native Fetch API performance

### 🔒 **Immutable by Design**

Thread-safe objects that prevent accidental mutations and race conditions.

## Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Error Handling](#error-handling)
- [Core API](#core-api)
- [Migration from CommonJS](#migration-from-commonjs)
- [Contributing](#contributing)

## Installation

```bash
npm install http-client-for-ts
```

### Requirements

- **Node.js** ≥ 18.0.0
- **TypeScript** ≥ 5.0.0

> **Note**: This library uses ESM modules and requires Node.js 18+ with native Fetch API support.

## Quick Start

```typescript
import { HttpClient, HttpRequest, HttpMethod } from 'http-client-for-ts';

// Define response type
interface User {
id: number;
name: string;
email: string;
}

const client = HttpClient.newHttpClient();

try {
// Build request
const request = HttpRequest.newBuilder()
.url("https://jsonplaceholder.typicode.com/users")
.method(HttpMethod.GET)
.header("Accept", "application/json")
.build();

// Send request and get response
const response = await client.send(request);

if (response.ok()) {
const users = response.body();
console.log('Found users:', users.length);
} else {
console.error('API Error:', response.statusCode());
}
} catch (error) {
console.error('Request failed:', error.message);
}
```

### POST Request with JSON Body

```typescript
import { MediaType, HttpHeaders } from 'http-client-for-ts';

const request = HttpRequest.newBuilder()
.url('https://api.example.com/users')
.method(HttpMethod.POST)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.body({
name: "John Doe",
email: "john@example.com"
})
.build();
```

## Error Handling

The library provides specific exception types for different error scenarios:

### Basic usage:

```typescript
import { HttpException } from 'http-client-for-ts';

// Other code

try {
const response = await client.send(request);

if (response.ok()) {
return response.body();
} else {
console.error('HTTP Error:', response.statusCode());
}
} catch (error) {
if (error instanceof HttpException) {
console.error('Request error:', error.message);
} else {
console.error('Unexpected error:', error);
}
}
```

### Advanced usage:

```typescript
import { HttpTimeoutException, HttpConnectException } from 'http-client-for-ts';

// Other code

try {
const response = await client.send(request);

if (response.httpStatus().is2xxSuccessful()) {
// Process successful response
return response.body();
} else if (response.httpStatus().is4xxClientError()) {
// Handle client error (authentication, validation, etc.)
throw new Error(`Client error: ${ response.statusCode() }`);
} else if (response.httpStatus().is5xxServerError()) {
// Handle server error
throw new Error(`Server error: ${ response.statusCode() }`);
}
} catch (error) {
if (error instanceof HttpTimeoutException) {
console.error("Request timeout");
} else if (error instanceof HttpConnectException) {
console.error("Connection failure");
} else {
console.error('Other error:', error.message);
}
}
```

## Core API

| Component | Description |
|----------------|------------------------------------------------------------|
| `HttpClient` | Main entry point for sending HTTP requests |
| `HttpRequest` | Immutable request configuration via builder pattern |
| `HttpResponse` | Typed response with status, headers, and deserialized body |
| `HttpStatus` | HTTP status codes with utility methods |
| `MediaType` | Constants for common MIME types |
| `HttpHeaders` | Constants for standard HTTP headers |

## Migration from CommonJS

If you're migrating from a CommonJS project:

```json
// package.json
{
"type": "module"
}
```

Or use dynamic imports for legacy projects:

```javascript
// For legacy projects that can't migrate to ESM yet
const { HttpClient } = await import('http-client-for-ts');
```

## Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

[MIT License](LICENSE) © Santiago Valencia Ochoa