Advanced Features

Advanced Features

api.vision includes powerful advanced features that let you debug, customize, and extend your APIs. This guide introduces these capabilities and how to leverage them effectively.

Request Inspector

The Request Inspector allows you to monitor, analyze, and debug API requests in real-time:

Real-Time Request Logging

Every request made to your API is logged and displayed in the dashboard in real-time. This includes the method, path, headers, query parameters, request body, and response details.

Request Filtering and Search

Filter requests by endpoint, method, status code, or search by content to quickly find specific requests in the log history.

Request Inspector Interface

Export and Share Requests

Export request logs for documentation or debugging purposes. You can share specific requests with your team to help troubleshoot issues or demonstrate behavior.

Breakpoint Debugging

Breakpoint debugging allows you to pause and inspect requests as they happen:

Set Breakpoints on Specific Routes

Configure breakpoints on specific routes or methods to pause request processing. When a request hits a breakpoint, it will be paused and displayed in the dashboard for inspection.

Modify Requests and Responses on the Fly

While a request is paused at a breakpoint, you can modify its content, headers, or body, and then continue processing with the modified data. You can also modify the response before it's sent back.

// Example: Setting a breakpoint in the dashboard
{
  "route": "/users/:id",
  "method": "GET",
  "enabled": true
}

Conditional Breakpoints

Set breakpoints that trigger only when specific conditions are met, such as when a request includes certain query parameters, headers, or body content.

// Example: Conditional breakpoint
{
  "route": "/products",
  "method": "GET",
  "condition": "request.query.price > 100",
  "enabled": true
}

Custom Scripting

Custom scripting allows you to add dynamic behavior to your API endpoints:

Write Custom Response Logic

Use JavaScript to create custom response handlers that can generate dynamic responses based on request data, simulate complex business logic, or mimic real-world API behavior.

// Example: Custom script for a login endpoint
module.exports = function(request, response) {
  const { username, password } = request.body;
  
  if (username === 'admin' && password === 'password') {
    return {
      status: 200,
      body: {
        token: 'jwt-token-example',
        user: {
          id: 1,
          username: 'admin',
          role: 'admin'
        }
      }
    };
  } else {
    return {
      status: 401,
      body: {
        error: 'Invalid credentials'
      }
    };
  }
}

Access the Request Context

Scripts have access to the full request context, including the URL, path parameters, query parameters, headers, and body.

// Accessing request data in scripts
module.exports = function(request, response) {
  console.log(request.path);        // Request path
  console.log(request.params);      // Path parameters
  console.log(request.query);       // Query parameters
  console.log(request.headers);     // Request headers
  console.log(request.body);        // Request body
  console.log(request.method);      // HTTP method
  
  // ... your logic here
}

Simulate Various Response Scenarios

Use scripts to simulate different response scenarios, including:

  • Success and error responses
  • Random failures or timeouts
  • Rate limiting
  • Conditional responses based on request data
  • Delayed responses to simulate network latency
// Example: Simulating random failures
module.exports = function(request, response) {
  // Simulate a 20% failure rate
  if (Math.random() < 0.2) {
    return {
      status: 500,
      body: {
        error: &apos;Internal Server Error&apos;,
        message: &apos;Something went wrong&apos;
      }
    };
  }
  
  // Normal response
  return {
    status: 200,
    body: {
      success: true,
      data: { /* ... */ }
    }
  };
}

Request Interceptors

Interceptors allow you to modify requests or responses globally across your API:

Request Modification

Intercept and modify incoming requests before they reach your endpoint handlers. This is useful for adding headers, transforming request data, or simulating authentication.

// Example: Request interceptor to add authentication
module.exports = function(request, next) {
  // Add a user ID to all requests
  request.headers[&apos;x-user-id&apos;] = &apos;123&apos;;
  
  // Continue to the next handler
  return next(request);
}

Response Modification

Intercept and modify outgoing responses before they're sent back to the client. This is useful for adding CORS headers, logging, or transforming response data.

// Example: Response interceptor to add CORS headers
module.exports = function(request, response, next) {
  // Process the response
  const modifiedResponse = next(request);
  
  // Add CORS headers
  modifiedResponse.headers[&apos;Access-Control-Allow-Origin&apos;] = &apos;*&apos;;
  modifiedResponse.headers[&apos;Access-Control-Allow-Methods&apos;] = &apos;GET, POST, PUT, DELETE, OPTIONS&apos;;
  modifiedResponse.headers[&apos;Access-Control-Allow-Headers&apos;] = &apos;Content-Type, Authorization&apos;;
  
  return modifiedResponse;
}

Global Error Handling

Implement global error handling to catch and process errors consistently across your API.

// Example: Global error handler
module.exports = function(error, request, response, next) {
  console.error(&apos;Error:&apos;, error);
  
  return {
    status: error.status || 500,
    body: {
      error: error.message || &apos;Internal Server Error&apos;,
      path: request.path
    }
  };
}

Authentication Simulation

api.vision allows you to simulate various authentication mechanisms:

JWT Authentication

Simulate JWT (JSON Web Token) authentication flows, including token issuance, validation, and expiration.

// Example: JWT authentication endpoint
module.exports = function(request, response) {
  const { username, password } = request.body;
  
  // Validate credentials
  if (username === &apos;user&apos; && password === &apos;password&apos;) {
    // Create a JWT token
    const token = &apos;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...&apos;;
    
    return {
      status: 200,
      body: {
        token,
        expires_in: 3600
      }
    };
  }
  
  return {
    status: 401,
    body: {
      error: &apos;Invalid credentials&apos;
    }
  };
}

OAuth2 Flows

Simulate OAuth2 authentication flows, including authorization code grant, implicit grant, and client credentials.

API Key Authentication

Implement API key authentication for your API, validating keys in headers, query parameters, or request bodies.

// Example: API key validation middleware
module.exports = function(request, next) {
  const apiKey = request.headers[&apos;x-api-key&apos;] || request.query.api_key;
  
  if (!apiKey || apiKey !== &apos;valid-api-key&apos;) {
    return {
      status: 401,
      body: {
        error: &apos;Invalid or missing API key&apos;
      }
    };
  }
  
  return next(request);
}

Simulated Network Conditions

Test your client applications under various network conditions:

Response Delays

Simulate network latency by adding configurable delays to your API responses.

// Example: Adding a random delay between 100-500ms
module.exports = function(request, response, next) {
  const result = next(request);
  
  // Add a random delay
  const delay = Math.floor(Math.random() * 400) + 100;
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(result);
    }, delay);
  });
}

Throttling

Simulate bandwidth limitations by throttling response data transfer rates.

Connection Issues

Simulate connection issues such as timeouts, server errors, or dropped connections to test how your client application handles failures.

// Example: Simulating timeouts for specific endpoints
module.exports = function(request, response, next) {
  if (request.path.includes(&apos;/slow-endpoint&apos;)) {
    // Timeout after 30 seconds
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          status: 504,
          body: {
            error: &apos;Gateway Timeout&apos;,
            message: &apos;Request timed out&apos;
          }
        });
      }, 30000);
    });
  }
  
  return next(request);
}

Data Persistence

api.vision provides options for persisting data between requests:

In-Memory Store

Store and retrieve data in memory for the duration of your API session. This is useful for simulating state across multiple requests.

// Example: Using the in-memory store
module.exports = function(request, response) {
  const store = request.store;
  
  // Get counter value or initialize it
  let counter = store.get(&apos;counter&apos;) || 0;
  
  // Increment counter
  counter++;
  
  // Store the new value
  store.set(&apos;counter&apos;, counter);
  
  return {
    status: 200,
    body: {
      counter
    }
  };
}

Persistent Storage

Save data to persistent storage that maintains state across server restarts. This is useful for long-running APIs or teams working with shared APIs.

Import/Export Data

Import initial data from JSON files or export current state for backup or sharing.

TypeScript Client Generation

Generate type-safe client libraries for your APIs:

Automatic TypeScript Definitions

api.vision can generate TypeScript interfaces and type definitions based on your resource schema, ensuring type safety when interacting with your API.

// Example: Generated TypeScript interfaces
export interface User {
  id: number;
  username: string;
  email: string;
  role: &apos;user&apos; | &apos;admin&apos;;
  createdAt: string;
}

export interface Post {
  id: number;
  title: string;
  content: string;
  userId: number;
  createdAt: string;
}

// Generated client
export class ApiClient {
  // Get all users
  async getUsers(): Promise<User[]> {
    // Implementation...
  }
  
  // Get user by ID
  async getUser(id: number): Promise<User> {
    // Implementation...
  }
  
  // Create user
  async createUser(user: Omit<User, &apos;id&apos; | &apos;createdAt&apos;>): Promise<User> {
    // Implementation...
  }
  
  // ... other methods
}

Client-Side Validation

The generated client includes validation logic to ensure your requests meet the API's requirements before they're sent, catching issues early in development.

Multiple Framework Support

Generate clients for different JavaScript/TypeScript frameworks and environments, including:

  • Browser (fetch API)
  • Node.js (axios)
  • React (react-query)
  • Angular (HttpClient)
  • Vue (axios)

Scheduled Tasks

Automate actions and simulate time-based events in your API:

Scheduled Data Updates

Set up tasks to modify your data at regular intervals, simulating real-world data changes.

// Example: Scheduled task configuration
{
  "name": "update-product-stock",
  "schedule": "*/30 * * * *",  // Every 30 minutes
  "handler": "scripts/update-stock.js"
}

Simulating Time-Based Events

Simulate events that occur at specific times, such as daily data refreshes, token expirations, or scheduled maintenance periods.

Webhooks and Notifications

Trigger webhooks or send notifications on a schedule to simulate asynchronous API behaviors.

// Example: Webhook task
{
  "name": "payment-callback",
  "schedule": "0 */2 * * *",  // Every 2 hours
  "action": {
    "type": "webhook",
    "url": "https://your-app.example.com/webhook",
    "method": "POST",
    "body": {
      "event": "payment_processed",
      "data": {
        "orderId": "12345",
        "status": "completed",
        "amount": 99.99
      }
    }
  }
}

Custom Server Extensions

Extend api.vision with custom functionality:

Custom Endpoints

Create entirely custom endpoints with specialized behavior that goes beyond standard REST operations.

WebSocket Support

Implement WebSocket endpoints for real-time communication between clients and your API.

// Example: WebSocket configuration
{
  "websockets": {
    "enabled": true,
    "path": "/ws",
    "handlers": {
      "connect": "scripts/ws-connect.js",
      "message": "scripts/ws-message.js",
      "disconnect": "scripts/ws-disconnect.js"
    }
  }
}

Third-Party Integrations

Integrate with third-party services or APIs to enhance your API capabilities.

Next Steps

To dive deeper into each advanced feature, check out the specific guides:

Tip: Starting Small

While api.vision offers many advanced features, you don't need to use them all right away. Start with the basics and gradually incorporate advanced features as your needs evolve. The platform is designed to be accessible to beginners while providing depth for advanced users.