@electi/typescript-rest-api-fetcher
v2025.11.14-1020
Published
Welcome to the comprehensive documentation for the **Type-Safe REST API Fetching Library**. This package is designed to make REST API calls type-safe and highly configurable. The primary goal is to ensure that your API requests are consistent, predictable
Keywords
Readme
Type-Safe REST API Fetching Library
Welcome to the comprehensive documentation for the Type-Safe REST API Fetching Library. This package is designed to make REST API calls type-safe and highly configurable. The primary goal is to ensure that your API requests are consistent, predictable, and fully typed, reducing the chances of runtime errors and enhancing the developer experience.
Key Features
- Type Safety: Ensures that all API requests and responses are typed, providing a safeguard against runtime errors.
- Configurable Mock Responses: Enables easy switching between real and mock API responses, facilitating testing and development without reliance on the actual backend.
- Detailed HTTP Status Handling: Robust error handling through detailed HTTP status codes, reducing the complexity of managing various server responses.
Installation
To get started with this package, simply install it via npm or yarn:
npm install @electi/typescript-rest-api-fetcher
# or
yarn add @electi/typescript-rest-api-fetcherUsage Overview
The library revolves around a few key classes and functions that help define and handle API requests. Below is a detailed explanation of these components.
DefaultRequestHeader Class
The DefaultRequestHeader class encapsulates all standard HTTP request headers. This class can be extended or used as-is to define headers for your API requests.
Example:
import { DefaultRequestHeader } from '@electi/typescript-rest-api-fetcher';
class MyRequestHeaders extends DefaultRequestHeader {
constructor() {
super();
this.authorization = 'Bearer my-token';
this.accept = 'application/json';
}
}HttpMethod Enum
The HttpMethod enum provides the standard HTTP methods for API requests. This ensures that only valid HTTP methods are used.
GETPOSTPUTDELETE
Example:
import { HttpMethod } from '@electi/typescript-rest-api-fetcher';
const method: HttpMethod = HttpMethod.POST;HttpStatus Class
The HttpStatus class is a powerful utility for handling HTTP status codes. It categorizes responses into informational, successful, redirection, client errors, and server errors. This makes it easier to interpret and handle responses appropriately.
Example:
import { HttpStatus } from '@electi/typescript-rest-api-fetcher';
if (response.status === HttpStatus.OK.value) {
console.log('Request was successful!');
}MockApiResponse Class
The MockApiResponse class is used to define mock responses for your API endpoints. This is particularly useful for testing and development, allowing you to simulate server responses without hitting a real API.
Example:
import { MockApiResponse, HttpStatus } from '@electi/typescript-rest-api-fetcher';
const mockResponse = MockApiResponse.createMockApiResponse(
{ data: 'mock data' },
HttpStatus.OK,
100, // 100ms query duration
false // offline status
);RestApiDefinition Class
The RestApiDefinition class allows you to define the structure of your API endpoints. This includes the method, path, expected statuses, and mock responses. It serves as the blueprint for each API request, ensuring consistency across your application.
Example:
import { RestApiDefinition, HttpMethod, HttpStatus, MockApiResponse } from '@electi/typescript-rest-api-fetcher';
const myApi = new RestApiDefinition(
'GetUserData',
HttpMethod.GET,
'/user/data',
[HttpStatus.OK],
MockApiResponse.createMockApiResponse({ user: 'John Doe' }, HttpStatus.OK),
true // Activate mock response
);handleRequest Function
The handleRequest function is the core of the library, where all API calls are made. It takes in a RestApiDefinition, along with request parameters, body, and headers, and returns a promise that resolves with the typed response.
Example:
import { handleRequest, RestApiDefinition, DefaultRequestHeader, HttpMethod, HttpStatus } from '@electi/typescript-rest-api-fetcherh';
const getUserData = new RestApiDefinition(
'GetUserData',
HttpMethod.GET,
'/user/data',
HttpStatus.OK,
MockApiResponse.createMockApiResponse({ user: 'John Doe' }, HttpStatus.OK)
);
const requestParams = {};
const requestBody = null;
const requestHeaders = new DefaultRequestHeader();
handleRequest(getUserData, requestParams, requestBody, requestHeaders)
.then(response => {
console.log(response);
})
.catch(error => {
console.error('Error fetching user data:', error);
});Error Handling
The library provides robust error handling via the RestClientErrorException class. It allows you to catch and handle different types of errors such as client errors, server errors, unexpected success responses, and network issues.
Example:
import { handleRequest, RestClientErrorException, RestApiDefinition, DefaultRequestHeader, HttpMethod, HttpStatus } from '@electi/typescript-rest-api-fetcher';
try {
const response = await handleRequest(getUserData, requestParams, requestBody, requestHeaders);
console.log(response);
} catch (error) {
if (error instanceof RestClientErrorException) {
console.error('An error occurred:', error.message);
// Handle specific error cases based on error.errorType
} else {
console.error('Unknown error:', error);
}
}RestClientErrorException Class
The RestClientErrorException class provides a structured way to deal with errors. It encapsulates the error type, HTTP status, and any additional information returned by the server.
Error Types:
- SERVER_ERROR: Indicates an issue on the server side.
- CLIENT_ERROR: Indicates a problem with the request made by the client.
- UNEXPECTED_SUCCESS_ERROR: Occurs when an unexpected success status code is returned.
- NETWORK_ERROR: Triggered when there is a network issue during the API call.
- INTERNAL_ERROR: Catch-all for any other unexpected issues.
Advanced Configuration
RestApiFetchConfig
This configuration object allows you to set global settings for your API requests, such as the API host, base path, and whether to use mock responses globally.
import { CONFIG } from '@electi/typescript-rest-api-fetcher';
CONFIG.API_HOST = 'https://api.example.com';
CONFIG.API_BASE_PATH = '/v1';
CONFIG.USE_MOCK_API_FOR_ALL_REQUESTS = true;Conclusion
This library is designed to simplify and streamline the process of making API requests in a type-safe manner. By leveraging the power of TypeScript, it ensures that your API interactions are reliable, predictable, and easy to maintain. Whether you’re building a small app or a large-scale enterprise solution, this package provides the tools you need to manage your API requests effectively.
Happy coding! 🎉
