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
- Visit SnakeQuery Dashboard
- Sign up or log in
- Navigate to Setup section
- 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.
- Use specific queries: βFind top 10 productsβ vs βShow all productsβ
- Define schemas: Structured responses are faster and more reliable
- Cache results: Store frequently used query results locally
- 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
| Header | Value | Required |
|---|
Content-Type | application/json | Yes |
Authorization | Bearer {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
}
interface QueryResponse {
response: any; // Query results
usageCount: {
totalTokens: number; // Total tokens used
promptTokens: number; // Input tokens
completionTokens: number; // Output tokens
};
}
HTTP Status Codes
| Code | Description |
|---|
200 | Success |
400 | Bad Request - Invalid query or parameters |
401 | Unauthorized - Invalid or missing API key |
402 | Payment Required - Insufficient credits |
429 | Rate Limit Exceeded |
500 | Internal Server Error |
504 | Gateway Timeout - Request took too long |
interface ErrorResponse {
error: string; // Error message
code?: string; // Error code
details?: object; // Additional error details
}
π¬ Getting Help