apizone
apizone is a comprehensive HTTP client package for JavaScript that combines the native simplicity of fetch with advanced features similar to Axios—and adds extra capabilities for robust HTTP communication. With apizone, you get:
- ⏱️ Timeout management: Automatically cancel requests if no response is received within a specified time (using AbortController).
- ♻️ Retry with exponential backoff: Automatically retry failed requests with an exponentially increasing delay.
- 🗂️ Internal caching for GET requests: Store GET responses internally to avoid redundant network calls.
- 🛠️ Interceptors: Add custom logic before requests are sent or after responses are received for modification or logging.
- 🔐 Authentication token management: Automatically attach an authentication token (e.g., JWT) to request headers.
- 📊 Progress event support: Monitor upload and download progress via callback functions.
- ⚠️ User-friendly error handling: Convert HTTP status codes into clear, descriptive error messages.
- ✉️ Full support for HTTP methods: Works with GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.
This package is designed to help you build robust, flexible, and high-performance applications with ease.
🔍 Table of Contents
- Introduction
- Features
- Installation
- Quick Start
- Usage
- Advanced Configuration
- Examples
- Contributing
- License
1. 📚 Introduction
The apizone package is a unified HTTP client built on the native fetch
API. It augments basic fetch functionality with advanced features like automatic retries with exponential backoff, internal caching, progress event support, request/response interceptors, timeout management using AbortController, and friendly error messages based on HTTP status codes. Additionally, it supports all standard HTTP methods.
2. ✨ Features
- Base URL: Set a default URL that is prepended to every request, reducing repetitive URL definitions.
- Timeout: Automatically cancel a request if no response is received within a specified time.
- Retry with Exponential Backoff: Automatically retry failed requests with an exponentially increasing delay.
- Internal Caching for GET Requests: Store GET responses internally (using a Map) to avoid redundant network calls.
- Interceptors: Add custom logic to modify or log requests and responses.
- Authentication Token Management: Automatically attach an authentication token (e.g., JWT) to every request.
- Progress Events: Monitor upload and download progress via callback functions.
- User-friendly Error Handling: Convert HTTP status codes into clear, descriptive error messages.
- Support for All HTTP Methods: Works with GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.
📝 Installation
You can install apizone using various package managers:
Using npm:
npm install apizone
Using Bower:
bower install apizone
Using Yarn:
yarn add apizone
Using pnpm:
pnpm add apizone
Using Bun:
bun add apizone
CDN Links
You can also use apizone directly in the browser via CDN:
unpkg:
<script src="https://unpkg.com/apizone@latest/dist/index.js"></script>
jsDelivr:
<script src="https://cdn.jsdelivr.net/npm/apizone@latest/dist/index.js"></script>
4. ⏱️ Quick Start
Here’s a basic example to get you started:
import API from 'apizone';
const api = new API({
baseURL: "https://fakestoreapi.com",
timeout: 10000, // 10 seconds timeout
retry: 3, // Retry failed requests 3 times
retryDelay: 1000, // Initial delay of 1000 ms; then 2000, 4000, etc.
cache: true, // Enable internal caching for GET requests
authToken: "your_jwt_token_here", // Optional authentication token
})
const getData = async () => {
try {
const response = await api.get("/products");
console.log("Products:", response.data);
} catch (error) {
console.error("Error:", error.errorMessage);
}
};
getData();
5. 📁 Usage
🔍 Setting Base URL
Configure a base URL so that you only need to specify endpoint paths:
const api = new API({
baseURL: "https://fakestoreapi.com",
});
⏱️ Timeout
Automatically cancel a request if no response is received within the specified duration:
const api = new API({
timeout: 10000, // 10 seconds
});
♻️ Retry with Exponential Backoff
Automatically retry failed requests with an exponentially increasing delay:
const api = new API({
retry: 3, // Retry up to 3 times
retryDelay: 1000, // 1000 ms initial delay; then 2000, 4000, etc.
});
🗂️ Internal Caching for GET Requests
Enable internal caching so that responses from GET requests are stored and reused:
await api.get("/products", { cache: true });
🛠️ Interceptors
Add custom logic to modify or log request and response data.
Request Interceptor:
api.addRequestInterceptor(async (config) => {
config.headers["x-custom-header"] = "myValue";
return config;
});
Response Interceptor:
api.addResponseInterceptor(async (response) => {
console.log("Response status:", response.status);
return response;
});
🔐 Authentication Token
Automatically attach an authentication token to every request header.
const api = new API({
authToken: "your_jwt_token_here",
});
📊 Progress Events
Monitor file upload or download progress using callback functions.
const formData = new FormData();
formData.append("file", fileInput.files[0]);
await api.post("/upload", formData, {
onUploadProgress: (e) => {
const percent = Math.round((e.loaded / e.total) * 100);
console.log(`Upload Progress: ${percent}%`);
},
});
⚠️ User-friendly Error Handling
Convert HTTP status codes into clear error messages for end users.
try {
await api.get("/non-existent-endpoint");
} catch (err) {
console.error(err.errorMessage);
// Example: "Not Found: The requested resource could not be found."
}
✉️ HTTP Methods
The API supports all standard HTTP methods:
// GET
await api.get("/products");
// POST
await api.post("/products", { title: "New Product", price: 29.99 });
// PUT
await api.put("/products/1", { title: "Updated Product", price: 19.99 });
// PATCH
await api.patch("/products/1", { price: 17.99 });
// DELETE
await api.delete("/products/1");
// HEAD
await api.head("/products");
// OPTIONS
await api.options("/products");
6. 💡 Advanced Configuration
Custom Retry Behavior
Customize the number of retries and delay between them:
const api = new API({
retry: 5,
retryDelay: 500, // 500 ms initial delay; subsequent delays increase exponentially.
});
Interceptors for Logging or Data Manipulation
Use interceptors to log or modify request and response data.
api.addRequestInterceptor(async (config) => {
console.log("Sending request to:", config.url);
return config;
});
api.addResponseInterceptor(async (response) => {
// Optionally modify the response data
return response;
});
Environment-Specific Settings
Customize your configuration based on your environment (e.g., browser or Node.js).
const api = new API({
baseURL: process.env.API_BASE_URL || "https://fakestoreapi.com",
timeout: 10000,
});
7. 📚 Examples
Example 1: Fetching Products with Caching
import API from 'apizone';
const api = new API({
baseURL: "https://fakestoreapi.com",
timeout: 10000,
cache: true,
});
const getData = async () => {
try {
const response = await api.get("/products");
console.log("Products:", response.data);
} catch (error) {
console.error("Error:", error.errorMessage);
}
};
getData();
Example 2: Creating a New Product with Authentication
import API from 'apizone';
const api = new API({
baseURL: "https://fakestoreapi.com",
authToken: "your_jwt_token_here",
timeout: 10000,
});
const postData = async () => {
try {
const newProduct = {
title: "New Product",
price: 49.99,
description: "A fantastic new product",
image: "https://i.pravatar.cc",
category: "electronics",
};
const response = await api.post("/products", newProduct);
console.log("Product Created:", response.data);
} catch (error) {
console.error("Error:", error.errorMessage);
}
};
postData();
8. 👨💼 Contributing
Contributions to apizone are welcome! Please follow these steps:
- ⭐ Fork the repository.
- 🔧 Create a feature branch for your changes.
- 📃 Commit your changes with clear and descriptive commit messages.
- 🔍 Submit a pull request with a detailed description of your changes.
Bug reports, feature requests, and general improvements are highly appreciated 🙌
9. 📄 License
This project is licensed under the MIT License.
Please see the LICENSE file for more details.