API Documentation
Complete guide to using the ZodForge Cloud API for AI-powered schema refinement
🚀 Getting Started
1. Get Your API Key
Sign up for a paid plan at zodforge.dev to receive your API key via email within minutes.
2. Base URL
https://web-production-f15d.up.railway.app 3. Make Your First Request
curl -X POST https://web-production-f15d.up.railway.app/api/v1/refine \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"schema": {
"code": "z.object({ email: z.string() })",
"typeName": "User",
"fields": { "email": "z.string()" }
},
"samples": [{ "email": "test@example.com" }]
}' 📦 TypeScript SDK
The official TypeScript SDK provides a type-safe, developer-friendly way to interact with the ZodForge API. No manual fetch calls, full IntelliSense support, and built-in retry logic.
Installation
npm install @zodforge/cloud zod Quick Start
Two simple ways to use the SDK:
Method 1: Client Instance (Recommended)
import { ZodForgeClient } from '@zodforge/cloud';
const client = new ZodForgeClient({
apiKey: 'zf_your_api_key_here'
});
const result = await client.refineSchema({
schema: {
code: 'z.object({ email: z.string() })',
typeName: 'User',
fields: { email: 'z.string()' }
},
samples: [
{ email: 'user@example.com' },
{ email: 'Admin@TEST.org' }
]
});
console.log(result.refinedSchema.code);
// z.object({ email: z.string().email().toLowerCase().trim() }) Method 2: Convenience Functions
import { refineSchema, setApiKey } from '@zodforge/cloud';
// Set API key globally
setApiKey('zf_your_api_key_here');
const result = await refineSchema({
schema: {
code: 'z.object({ price: z.number(), currency: z.string() })',
typeName: 'Product',
fields: { price: 'z.number()', currency: 'z.string()' }
},
samples: [
{ price: 100, currency: 'USD' },
{ price: 50, currency: 'EUR' }
]
});
// Check semantic relationships (Context Reasoning)
console.log(result.refinedSchema.relationships);
// [{
// fields: ['price', 'currency'],
// pattern: 'monetary_value',
// suggestion: 'Consider creating a Money type...',
// confidence: 0.92
// }] Advanced Features
🧠 Context Reasoning
The AI detects semantic relationships between fields:
// AI automatically detects lat+lng relationship
const result = await client.refineSchema({
schema: {
code: 'z.object({ lat: z.number(), lng: z.number() })',
typeName: 'Location',
fields: { lat: 'z.number()', lng: 'z.number()' }
},
samples: [
{ lat: 51.5074, lng: -0.1278 }, // London
{ lat: 40.7128, lng: -74.0060 } // New York
]
});
// Check detected relationships
result.refinedSchema.relationships.forEach(rel => {
console.log(`Pattern: ${rel.pattern}`); // "geolocation"
console.log(`Confidence: ${rel.confidence}`); // 0.95
console.log(`Suggestion: ${rel.suggestion}`);
}); 🔍 Enhanced Explainability
Every improvement includes full traceability:
result.refinedSchema.improvements.forEach(imp => {
console.log(`Field: ${imp.field}`);
console.log(`Source: ${imp.sourceSnippet}`); // Actual sample data
console.log(`Pattern: ${imp.detectedPattern}`); // e.g., "email_format"
console.log(`Rule: ${imp.ruleApplied}`); // e.g., "RFC5322_email"
console.log(`Change: ${imp.before} → ${imp.after}`);
}); ⚡ Response Caching
Identical requests are cached for instant responses:
// First call: ~9 seconds (AI processing)
const result1 = await client.refineSchema(request);
console.log(result1.processingTime); // ~9000ms
// Second identical call: <1ms (cached)
const result2 = await client.refineSchema(request);
console.log(result2.cached); // true
console.log(result2.processingTime); // <1ms Other SDK Features
- Health Check:
await client.getHealth() - Usage Stats:
await client.getUsage() - Error Handling: Built-in retry logic with exponential backoff
- TypeScript Support: Full type definitions with IntelliSense
- Zero Dependencies: No runtime dependencies (only Zod as peer dep)
- Dual Module: CommonJS + ESM support
🔑 Authentication
All API requests require authentication using Bearer tokens (your API key).
Authorization Header
Authorization: Bearer zf_your_api_key_here ⚠️ Security Best Practices
- Never commit API keys to version control
- Store keys in environment variables (
ZODFORGE_API_KEY) - Use separate keys for development, staging, and production
- Rotate keys regularly (every 90 days recommended)
📡 API Endpoints
/api/v1/health
Check API status and service health. No authentication required.
Request
curl https://web-production-f15d.up.railway.app/api/v1/health Response (200)
{
"status": "healthy",
"version": "1.0.0",
"uptime": 123456,
"timestamp": "2025-10-20T18:00:00.000Z",
"services": {
"openai": "up",
"anthropic": "up"
}
} /api/v1/refine
AI-powered schema refinement. Analyzes your Zod schema and sample data to suggest intelligent improvements.
Request Body
{
"schema": {
"code": "z.object({ email: z.string(), age: z.number() })",
"typeName": "User",
"fields": {
"email": "z.string()",
"age": "z.number()"
}
},
"samples": [
{ "email": "alice@example.com", "age": 28 },
{ "email": "bob@test.org", "age": 35 }
]
} Parameters
| Field | Type | Description |
|---|---|---|
schema.code | string | Original Zod schema code |
schema.typeName | string | Name of the schema (e.g., "User") |
schema.fields | object | Field name → Zod definition mapping |
samples | array | Sample data objects (1-10 recommended) |
Response (200)
{
"success": true,
"refinedSchema": {
"code": "z.object({\n email: z.string().email().toLowerCase(),\n age: z.number().int().min(0).max(150)\n})",
"improvements": [
{
"field": "email",
"before": "z.string()",
"after": "z.string().email().toLowerCase()",
"reason": "Detected email pattern. Added validation and normalization.",
"confidence": 0.98
},
{
"field": "age",
"before": "z.number()",
"after": "z.number().int().min(0).max(150)",
"reason": "Age should be realistic integer. Added constraints.",
"confidence": 0.95
}
],
"confidence": 0.96
},
"suggestions": [
"Consider adding .trim() to email for better normalization",
"You might want .describe() for better documentation"
],
"metadata": {
"creditsUsed": 1,
"creditsRemaining": 4999,
"processingTime": 1247,
"aiProvider": "openai",
"modelUsed": "gpt-4-turbo"
}
} Error Responses
{
"error": "Unauthorized",
"message": "Invalid or missing API key"
} {
"error": "Validation Error",
"message": "Invalid request body",
"details": [
{
"field": "schema.code",
"issue": "Required field missing"
}
]
} {
"error": "Rate Limit Exceeded",
"message": "Too many requests. Please try again later.",
"retryAfter": 60
} 💻 Code Examples
cURL
curl -X POST https://web-production-f15d.up.railway.app/api/v1/refine \
-H "Authorization: Bearer ${ZODFORGE_API_KEY}" \
-H "Content-Type: application/json" \
-d @request.json Node.js / TypeScript
import fetch from 'node-fetch';
const API_KEY = process.env.ZODFORGE_API_KEY;
const API_URL = 'https://web-production-f15d.up.railway.app/api/v1/refine';
async function refineSchema(schema, samples) {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ schema, samples }),
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return await response.json();
}
// Usage
const result = await refineSchema(
{
code: 'z.object({ email: z.string() })',
typeName: 'User',
fields: { email: 'z.string()' }
},
[{ email: 'test@example.com' }]
);
console.log(result.refinedSchema.code); Python
import os
import requests
API_KEY = os.getenv('ZODFORGE_API_KEY')
API_URL = 'https://web-production-f15d.up.railway.app/api/v1/refine'
def refine_schema(schema, samples):
response = requests.post(
API_URL,
headers={
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
},
json={'schema': schema, 'samples': samples}
)
response.raise_for_status()
return response.json()
# Usage
result = refine_schema(
schema={
'code': 'z.object({ email: z.string() })',
'typeName': 'User',
'fields': {'email': 'z.string()'}
},
samples=[{'email': 'test@example.com'}]
)
print(result['refinedSchema']['code']) ZodForge CLI
The easiest way to use ZodForge Cloud is through the CLI:
# Install CLI
npm install -g zodforge
# Set API key
export ZODFORGE_API_KEY=your_key_here
# Generate schema with cloud refinement
zodforge generate input.json --cloud
# Or from URL
zodforge generate https://api.example.com/data --cloud ⏱️ Rate Limits
| Plan | Monthly Limit | Hourly Limit | Response |
|---|---|---|---|
| Free | 100 requests | 10 requests | 429 when exceeded |
| Pro | 5,000 requests | 100 requests | 429 when exceeded |
| Enterprise | Unlimited | Custom | Fair use policy |
💡 Tip: Rate Limit Headers
Check response headers for rate limit info:
X-RateLimit-Limit- Your hourly limitX-RateLimit-Remaining- Requests remainingX-RateLimit-Reset- When limit resets (Unix timestamp)
✨ Best Practices
Optimal Sample Data
- Provide 3-10 diverse samples
- Include edge cases (empty, null, extreme values)
- Use real-world data when possible
- Ensure samples match schema structure
Error Handling
- Always check response status codes
- Implement exponential backoff for 429 errors
- Log failed requests for debugging
- Have fallback for API unavailability
Performance
- Cache refined schemas when possible
- Batch similar schemas together
- Set reasonable timeouts (30s recommended)
- Monitor API latency and credits
Security
- Never expose API keys in client code
- Use HTTPS for all requests
- Rotate keys every 90 days
- Monitor usage for anomalies