react-service-base-api
v0.0.1
Published
A TypeScript-based API client library with built-in error handling, authentication support, and mock capabilities for development
Maintainers
Readme
BaseApi
A TypeScript-based API client library with built-in error handling, authentication support, and mock capabilities for development.
Features
- 🚀 Simple & Intuitive: Easy-to-use API client with a clean interface
- 🔒 Authentication Support: Built-in token-based authentication handling
- 🛡️ Error Handling: Comprehensive error handling with custom error types
- 🧪 Mock Support: Built-in mock API responses for development and testing
- 📝 TypeScript: Full TypeScript support with proper type definitions
- 🔄 HTTP Methods: Support for GET, POST, PUT, DELETE operations
Installation
npm install baseapiQuick Start
import { apiClient, ApiResponse } from 'baseapi';
// Basic GET request
const response = await apiClient.get<User[]>('/users');
console.log(response.data);
// POST request with data
const newUser = await apiClient.post<User>('/users', {
name: 'John Doe',
email: '[email protected]'
});
// Authentication
apiClient.setAuthToken('your-jwt-token');
const protectedData = await apiClient.get<ProtectedData>('/protected');API Reference
ApiClient
The main API client class that handles HTTP requests.
Constructor
new ApiClient(baseURL?: string)baseURL(optional): Base URL for all API requests. Defaults to/api
Methods
get<T>(endpoint: string, params?: Record<string, any>): Promise<ApiResponse<T>>
Performs a GET request.
post<T>(endpoint: string, data?: any): Promise<ApiResponse<T>>
Performs a POST request with optional data.
put<T>(endpoint: string, data?: any): Promise<ApiResponse<T>>
Performs a PUT request with optional data.
delete<T>(endpoint: string): Promise<ApiResponse<T>>
Performs a DELETE request.
setAuthToken(token: string): void
Sets the authorization token for subsequent requests.
removeAuthToken(): void
Removes the authorization token.
Types
ApiResponse<T>
interface ApiResponse<T> {
data: T;
success: boolean;
message?: string;
error?: string;
}ApiError
interface ApiError {
message: string;
status?: number;
code?: string;
}Mock API Support
For development and testing, you can use the mock API response helper:
import { mockApiResponse } from 'baseapi';
// Mock a successful response with 500ms delay
const mockUsers = await mockApiResponse([
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
], 500);Error Handling
The library provides comprehensive error handling:
try {
const response = await apiClient.get<User>('/users/123');
console.log(response.data);
} catch (error) {
if (error instanceof ApiError) {
console.error(`API Error: ${error.message} (Status: ${error.status})`);
} else {
console.error('Unexpected error:', error);
}
}Development
# Install dependencies
npm install
# Build the project
npm run build
# Watch for changes during development
npm run dev
# Run the example
npm startLicense
MIT License - see LICENSE file for details.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Changelog
1.0.0
- Initial release
- Basic API client functionality
- Authentication support
- Mock API capabilities
- TypeScript support
