Skip to main content

Overview

Backend Services Only: This Fetch API implementation is designed for server-side applications and backend services. For client-side applications, use the Node.js SDK or Python SDK instead to ensure proper API key security.
Use SnakeQuery in server-side JavaScript environments with the native Fetch API. Perfect for backend services, server-side applications, and secure API integrations where your API key can be safely stored.

🎯 What is SnakeQuery?

SnakeQuery transforms natural language into structured data queries using AI. Instead of writing complex filtering, mapping, and aggregation logic, simply describe what you want in plain language.

πŸš€ Quick Start

Get Your API Key

  1. Visit SnakeQuery Dashboard
  2. Sign up or log in
  3. Navigate to Setup section
  4. Copy API key

Basic Usage

async function queryWithFetch() {
  const apiKey = 'your-api-key-here';
  const baseUrl = 'https://app.snakequery.com/api';
  
  const requestData = {
    query: 'Find products under $100',
    data: [
      { name: 'iPhone 14', price: 999, category: 'electronics' },
      { name: 'Coffee Mug', price: 19, category: 'home' },
      { name: 'Notebook', price: 15, category: 'office' }
    ]
  };
  
  try {
    const response = await fetch(`${baseUrl}/query`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
      },
      body: JSON.stringify(requestData)
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const result = await response.json();
    console.log('Results:', result.response);
    console.log('Tokens used:', result.usageCount.totalTokens);
  } catch (error) {
    console.error('Query failed:', error.message);
  }
}

queryWithFetch();

πŸ“Š Structured Responses with Schema

For production applications, define response schemas to ensure consistent, type-safe results:
async function structuredQuery() {
  const apiKey = 'your-api-key-here';
  const baseUrl = 'https://app.snakequery.com/api';
  
  // Define response schema
  const productSchema = {
    type: 'array',
    items: {
      type: 'object',
      properties: {
        productName: { type: 'string' },
        price: { type: 'number', minimum: 0 },
        category: { type: 'string' }
      },
      required: ['productName', 'price']
    }
  };
  
  const requestData = {
    query: 'Show all electronics products with their names, prices, and categories',
    data: [
      { name: 'MacBook Pro', price: 2399, category: 'electronics', rating: 4.8 },
      { name: 'iPad Air', price: 599, category: 'electronics', rating: 4.5 },
      { name: 'Coffee Maker', price: 89, category: 'home', rating: 4.2 }
    ],
    responseSchema: productSchema
  };
  
  try {
    const response = await fetch(`${baseUrl}/query`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
      },
      body: JSON.stringify(requestData)
    });
    
    const result = await response.json();
    console.log('Structured results:', result.response);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

🌐 Querying External APIs

Query data from any REST API endpoint by providing a URL instead of direct data:
async function queryExternalAPI() {
  const apiKey = 'your-api-key-here';
  const baseUrl = 'https://app.snakequery.com/api';
  
  const resultSchema = {
    type: 'array',
    items: {
      type: 'object',
      properties: {
        title: { type: 'string' },
        price: { type: 'number', minimum: 0 },
        category: { type: 'string' }
      },
      required: ['title', 'price']
    }
  };
  
  const requestData = {
    query: 'Find products under $100, show title, price and category',
    fetchUrl: 'https://api.escuelajs.co/api/v1/products',
    responseSchema: resultSchema
  };
  
  try {
    const response = await fetch(`${baseUrl}/query`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
      },
      body: JSON.stringify(requestData)
    });
    
    const result = await response.json();
    console.log('External API results:', result.response);
    console.log('Found', result.response.length, 'products under $100');
  } catch (error) {
    console.error('Error:', error.message);
  }
}

πŸ”§ Environment Setup

Environment Variables

For production backend applications, store your API key securely using environment variables:
// Server-side environment variables
const apiKey = process.env.SNAKE_QUERY_API_KEY;

// Never expose API keys in client-side code
// Use backend proxy endpoints for frontend applications

Reusable Query Function

Create a reusable function for your application:
class SnakeQueryClient {
  constructor(apiKey, baseUrl = 'https://app.snakequery.com/api') {
    this.apiKey = apiKey;
    this.baseUrl = baseUrl;
  }
  
  async query(options) {
    const { query, data, fetchUrl, responseSchema } = options;
    
    const requestData = {
      query,
      ...(data && { data }),
      ...(fetchUrl && { fetchUrl }),
      ...(responseSchema && { responseSchema })
    };
    
    const response = await fetch(`${this.baseUrl}/query`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.apiKey}`
      },
      body: JSON.stringify(requestData)
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(
        errorData.error || `HTTP error! status: ${response.status}`
      );
    }
    
    return await response.json();
  }
}

// Usage
const client = new SnakeQueryClient('your-api-key-here');

const result = await client.query({
  query: 'Find top 5 expensive products',
  fetchUrl: 'https://api.store.com/products'
});

🎯 Common Use Cases

1. E-commerce Product Filtering

async function filterProducts() {
  const client = new SnakeQueryClient('your-api-key');
  
  const result = await client.query({
    query: 'Show electronics under $500, sorted by price',
    fetchUrl: 'https://api.store.com/products',
    responseSchema: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          name: { type: 'string' },
          price: { type: 'number' },
          category: { type: 'string' }
        }
      }
    }
  });
  
  return result.response;
}

2. Data Analytics Dashboard

async function getSalesAnalytics() {
  const client = new SnakeQueryClient('your-api-key');
  
  const result = await client.query({
    query: 'Calculate monthly revenue and show trends',
    fetchUrl: 'https://api.company.com/sales',
    responseSchema: {
      type: 'object',
      properties: {
        monthlyRevenue: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              month: { type: 'string' },
              revenue: { type: 'number' }
            }
          }
        },
        trend: { type: 'string' }
      }
    }
  });
  
  return result.response;
}

3. User Management

async function getActiveUsers() {
  const client = new SnakeQueryClient('your-api-key');
  
  const result = await client.query({
    query: 'List active users with their roles and last login',
    fetchUrl: 'https://api.company.com/users',
    responseSchema: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          username: { type: 'string' },
          role: { type: 'string' },
          lastLogin: { type: 'string' },
          isActive: { type: 'boolean' }
        }
      }
    }
  });
  
  return result.response;
}

⚠️ Error Handling

HTTP Status Codes

async function handleErrors() {
  const client = new SnakeQueryClient('your-api-key');
  
  try {
    const result = await client.query({
      query: 'Analyze data',
      data: myData
    });
    
    return result.response;
  } catch (error) {
    // Parse error response
    if (error.message.includes('401')) {
      console.error('Invalid API key');
    } else if (error.message.includes('402')) {
      console.error('Insufficient credits');
    } else if (error.message.includes('500')) {
      console.error('Server error');
    } else if (error.message.includes('504')) {
      console.error('Request timeout');
    } else {
      console.error('Unknown error:', error.message);
    }
    
    return null;
  }
}

Network Error Handling

async function robustQuery(queryOptions, retries = 3) {
  const client = new SnakeQueryClient('your-api-key');
  
  for (let i = 0; i < retries; i++) {
    try {
      return await client.query(queryOptions);
    } catch (error) {
      if (error.message.includes('Network') && i < retries - 1) {
        // Wait before retrying
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
        continue;
      }
      throw error;
    }
  }
}

πŸ”’ Security Best Practices

API Key Protection

// βœ… Correct: Server-side usage with environment variables
const apiKey = process.env.SNAKE_QUERY_API_KEY;

// ❌ Never expose API keys in client-side code
const apiKey = 'sk-1234567890abcdef...'; // DON'T DO THIS

// βœ… Backend proxy endpoint for frontend applications
app.post('/api/snake-query', async (req, res) => {
  try {
    const response = await fetch('https://app.snakequery.com/api/query', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.SNAKE_QUERY_API_KEY}`
      },
      body: JSON.stringify(req.body)
    });
    
    const result = await response.json();
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

Backend Security

Server-Side Only: This implementation should only be used in secure server environments where API keys cannot be exposed to end users.
For applications with frontend components, create backend endpoints that proxy requests to SnakeQuery API.

⚑ Performance Tips

  1. Use specific queries: β€œFind top 10 products” vs β€œShow all products”
  2. Define schemas: Structured responses are faster and more reliable
  3. Cache results: Store frequently used query results locally
  4. Batch related queries: Combine multiple questions into one query

πŸŽ‰ Next Steps

  • Recommended: Use Node.js SDK for easier server-side integration
  • Explore Python SDK for data science and backend workflows
  • Learn Schema Building for structured responses
  • Set up proper backend proxy endpoints for frontend applications

πŸ“š API Reference

Core Endpoint

POST https://app.snakequery.com/api/query

Headers

HeaderValueRequired
Content-Typeapplication/jsonYes
AuthorizationBearer {api_key}Yes

Request Body

interface QueryRequest {
  query: string;                    // Natural language query
  data?: any[];                     // Direct data to query
  fetchUrl?: string;                // External API URL to fetch and query
  responseSchema?: object;          // JSON schema for structured response
}

Response Format

interface QueryResponse {
  response: any;                    // Query results
  usageCount: {
    totalTokens: number;            // Total tokens used
    promptTokens: number;           // Input tokens
    completionTokens: number;       // Output tokens
  };
}

HTTP Status Codes

CodeDescription
200Success
400Bad Request - Invalid query or parameters
401Unauthorized - Invalid or missing API key
402Payment Required - Insufficient credits
429Rate Limit Exceeded
500Internal Server Error
504Gateway Timeout - Request took too long

Error Response Format

interface ErrorResponse {
  error: string;                    // Error message
  code?: string;                    // Error code
  details?: object;                 // Additional error details
}

πŸ’¬ Getting Help

⌘I