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
- Host: GitHub
- URL: https://github.com/santiagovogit/http-client-for-ts
- Owner: SantiagoVOGIT
- License: mit
- Created: 2024-12-02T20:43:55.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-12-30T15:41:57.000Z (over 1 year ago)
- Last Synced: 2025-03-24T08:22:38.494Z (over 1 year ago)
- Topics: api, fetch, fetch-api, http, http-client, http-requests, java, request, typescript, typescript-library
- Language: TypeScript
- Homepage:
- Size: 49.8 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# http-client-for-ts
[](https://badge.fury.io/js/http-client-for-ts)[](https://opensource.org/licenses/MIT)
[](https://www.typescriptlang.org/)
[](https://nodejs.org/)
[]()
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