Apisto Basics & Setup

Learn the core concepts and get started with Apisto in minutes

Beginner 15 min read

What is Apisto?

Apisto is a comprehensive, universal API client for JavaScript that provides everything you need for modern web development. It combines the simplicity of fetch with enterprise-grade features like automatic retries, file handling, authentication, and real-time capabilities.

💡 Why Apisto? While fetch() and Axios are great, Apisto provides a unified solution for complex API interactions without needing multiple libraries.

Installation

🌐 CDN (Browser)


<script src="https://cdn.jsdelivr.net/npm/apisto-client/dist/apisto.min.js"></script>
<script>
  const api = new Apisto({
    baseURL: 'https://api.example.com'
  });
</script>
            

📦 NPM (Node.js)


npm install apisto-client
            

import { Apisto } from 'apisto-client';

const api = new Apisto({
  baseURL: 'https://api.example.com'
});
            

Basic Configuration

Apisto is highly configurable. Here are the essential configuration options:


const api = new Apisto({
  // Required: Your API base URL
  baseURL: 'https://api.example.com',
  
  // Request timeout in milliseconds (default: 30000)
  timeout: 10000,
  
  // Maximum retry attempts (default: 3)
  maxRetries: 3,
  
  // Base delay for exponential backoff (default: 1000ms)
  retryBaseDelay: 1000,
  
  // Enable circuit breaker pattern (default: true)
  enableCircuitBreaker: true,
  
  // Enable rate limiting (default: true)
  enableRateLimiting: true,
  
  // Default headers for all requests
  defaultHeaders: {
    'Content-Type': 'application/json',
    'X-Client-Version': '1.0.0'
  },
  
  // Enable request/response logging (default: true)
  enableLogging: true,
  
  // Maximum concurrent requests (default: 10)
  maxConcurrent: 5,
  
  // Rate limiting configuration
  rateLimit: {
    max: 100,        // Maximum requests
    window: 60000    // Time window in milliseconds (1 minute)
  }
});
        

⚠️ Important: The baseURL is required. All other configuration options have sensible defaults.

Core Concepts

1. Request Lifecycle

Every request goes through a well-defined lifecycle with interceptors, retry logic, and error handling.

  1. Pre-request: Interceptors and authentication
  2. Execution: Fetch with timeout and cancellation
  3. Retry: Exponential backoff on failures
  4. Response: Parsing and interceptors
  5. Error Handling: Structured error classes

2. Error Handling

Apisto provides structured error classes for different types of failures.


try {
  const data = await api.get('/users');
} catch (error) {
  if (error instanceof ApiError) {
    // HTTP errors (4xx, 5xx)
    console.log('API Error:', error.status, error.body);
  } else if (error instanceof NetworkError) {
    // Network failures
    console.log('Network error:', error.message);
  } else if (error instanceof ApistoError) {
    // Apisto-specific errors
    console.log('Apisto error:', error.code);
  }
}
            

3. Interceptors

Modify requests and responses globally using interceptors.


// Request interceptor
api.addRequestInterceptor(async (options, url) => {
  // Add timestamp to all requests
  options.headers['X-Request-Timestamp'] = Date.now();
  return options;
});

// Response interceptor
api.addResponseInterceptor(async (response, options) => {
  // Log response time
  console.log(`Response received in ${Date.now() - options.headers['X-Request-Timestamp']}ms`);
  return response;
});

// Error interceptor
api.addErrorInterceptor(async (error, options) => {
  // Send errors to monitoring service
  console.error('Request failed:', error);
  return error;
});
            

Quick Example

Let's see Apisto in action with a complete example:


// Initialize Apisto
const api = new Apisto({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 10000,
  maxRetries: 2
});

// Add request interceptor for logging
api.addRequestInterceptor(async (options, url) => {
  console.log(`🚀 Making ${options.method} request to: ${url}`);
  return options;
});

// Add response interceptor
api.addResponseInterceptor(async (response, options) => {
  console.log(`✅ Received response with status: ${response.status}`);
  return response;
});

// Usage example
async function fetchUserData() {
  try {
    // Get all users
    const users = await api.get('/users');
    console.log('Users:', users);
    
    // Get specific user
    const user = await api.get('/users/1');
    console.log('User 1:', user);
    
    // Create new user
    const newUser = await api.post('/users', {
      name: 'John Doe',
      email: 'john@example.com'
    });
    console.log('Created user:', newUser);
    
  } catch (error) {
    console.error('Failed to fetch user data:', error);
  }
}

// Run the example
fetchUserData();
        

🎉 Congratulations! You've just learned the basics of Apisto. Try running this example in your browser console to see it in action!

Ready for the next step?

Now that you understand the basics, let's dive into making different types of HTTP requests.

Continue to Request Methods →