Quick Start
Get up and running with X-Router in just a few minutes!
Step 1: Get USDC on Base Mainnet
You need USDC on the Base network to pay for API requests.
Option A: Purchase on Exchange
- Buy USDC on a centralized exchange (Coinbase, Binance, Kraken)
- Withdraw directly to the Base network
- Use your Ethereum wallet address
Option B: Bridge from Ethereum
- Visit bridge.base.org
- Connect your wallet
- Bridge USDC from Ethereum Mainnet to Base
- Wait a few minutes for the bridge to complete
Step 2: Install Dependencies
Install the x402-fetch library and viem for wallet management:
npm install x402-fetch viemOr with other package managers:
yarn add x402-fetch viem
# or
pnpm add x402-fetch viemStep 3: Set Up Your Wallet
Security Warning: Never commit your private key to version control! Always use environment variables and add .env to .gitignore.
Create a .env file with your private key:
PRIVATE_KEY=0x1234567890abcdef...Add it to .gitignore:
echo ".env" >> .gitignoreStep 4: Make Your First Request
Create a simple script to test the API:
// index.ts
import 'dotenv/config';
import { wrapFetchWithPayment } from 'x402-fetch';
import { privateKeyToAccount } from 'viem/accounts';
// Set up payment-enabled fetch
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const fetchWithPayment = wrapFetchWithPayment(fetch, account);
async function main() {
console.log('Making request to X-Router...');
const response = await fetchWithPayment('https://api.x-router.ai/v1/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: [
{ role: 'user', content: 'Hello! What is 2+2?' }
],
model: 'anthropic/claude-3.5-sonnet',
max_tokens: 100
})
});
const data = await response.json();
console.log('Response:', data.content);
console.log('Tokens used:', data.usage.total_tokens);
console.log('Model:', data.model);
}
main();Run it:
npx tsx index.ts
# or with Node.js
node --loader ts-node/esm index.tsStep 5: Try Different Models
List all available models:
const response = await fetch('https://api.x-router.ai/v1/models');
const data = await response.json();
console.log(`Total models: ${data.total}`);
console.log('First 5 models:');
data.models.slice(0, 5).forEach(model => {
console.log(`- ${model.id}: ${model.name}`);
});Step 6: Get Cost Estimates
Use the estimate endpoint to check costs before making requests:
const estimateResponse = await fetch('https://api.x-router.ai/v1/estimate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: [
{ role: 'user', content: 'Explain quantum computing in simple terms' }
],
model: 'anthropic/claude-3.5-sonnet',
max_tokens: 500
})
});
const estimate = await estimateResponse.json();
console.log(`Estimated cost: $${estimate.estimatedCost.usd}`);
console.log(`Input tokens: ${estimate.estimatedInputTokens}`);
console.log(`Output tokens: ${estimate.estimatedOutputTokens}`);Step 7: Enable Streaming
Get real-time responses with streaming:
const response = await fetchWithPayment('https://api.x-router.ai/v1/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: [
{ role: 'user', content: 'Tell me a short story about AI.' }
],
model: 'anthropic/claude-3.5-sonnet',
max_tokens: 200,
stream: true // Enable streaming
})
});
// Parse SSE stream
const reader = response.body?.getReader();
if (!reader) throw new Error('No response body');
const decoder = new TextDecoder();
let fullContent = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') {
console.log('\n[Stream complete]');
break;
}
try {
const json = JSON.parse(data);
const content = json.choices?.[0]?.delta?.content || '';
if (content) {
process.stdout.write(content); // Print in real-time
fullContent += content;
}
} catch (e) {
// Skip invalid JSON
}
}
}
}Next Steps
Now that you have X-Router working, explore:
- Chat Completions API - Detailed API documentation
- Basic Usage Examples - Common usage patterns
- Streaming Responses - Enable real-time responses
- Image Generation - Generate images with AI
Troubleshooting
Insufficient USDC Balance
Error: Insufficient USDC balance for paymentSolution: Add more USDC to your wallet on Base network.
Invalid Private Key
Error: Invalid private key formatSolution: Ensure your private key starts with 0x and is a valid hex string.
Network Issues
Error: Failed to connect to APISolution: Check your internet connection and try again.
Rate Limit Exceeded
Error: Too many requestsSolution: The API limits requests to 100 per minute per IP address. Wait a minute and try again, or implement retry logic with exponential backoff. See Rate Limits for details and best practices.
Payment Amount Exceeds Maximum
Error: Payment amount exceeds maximum allowedSolution: The x402-fetch library has a default spending limit (~$0.10 per request). For premium models or high-resolution images, increase the limit:
const fetchWithPayment = wrapFetchWithPayment(fetch, account, {
maxAmountPerRequest: 5.0, // Allow up to $5 per request
});See Spending Limits for recommended values.
Need Help?
- Check the Chat Completions API for detailed documentation
- Review the Usage Guides for common patterns
- Report issues on GitHub