Usage Examples
Practical examples for various programming languages and use cases
cURL Examples
Starting Position Analysis
curl -X POST https://stockfish-api.didi.web.id/api/v1/analyze \
-H "Content-Type: application/json" \
-d '{"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "depth": 15}'
MultiPV Analysis
curl -X POST https://stockfish-api.didi.web.id/api/v1/analyze \
-H "Content-Type: application/json" \
-d '{"fen": "r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 4 4", "depth": 12, "multipv": 3}'
Time-based Analysis
curl -X POST https://stockfish-api.didi.web.id/api/v1/analyze \
-H "Content-Type: application/json" \
-d '{"fen": "r3k2r/ppp2ppp/2n5/3qp3/2B1P3/2N2N2/PPPP1PPP/R1BQK2R w KQkq - 0 5", "time": 5000}'
JavaScript (Fetch API)
Basic Analysis
const analyzePosition = async (fen, depth = 15) => {
const response = await fetch('https://stockfish-api.didi.web.id/api/v1/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ fen, depth })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
};
// Usage
const fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
const result = await analyzePosition(fen);
console.log(result);
MultiPV Analysis
const multiPVAnalysis = async (fen, multipv = 3, depth = 12) => {
const response = await fetch('https://stockfish-api.didi.web.id/api/v1/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ fen, depth, multipv })
});
const data = await response.json();
return data;
};
// Get top 3 best moves
const result = await multiPVAnalysis('r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 4 4', 3);
result.evaluations.forEach(eval => {
console.log(`Depth ${eval.depth}: ${eval.score_cp || eval.score_mate} centipawns`);
});
Python (requests)
Basic Analysis
import requests
import json
def analyze_position(fen, depth=15, multipv=1, time=1000):
"""Analyze a chess position using the Stockfish API."""
url = 'https://stockfish-api.didi.web.id/api/v1/analyze'
payload = {
'fen': fen,
'depth': depth,
'multipv': multipv,
'time': time
}
try:
response = requests.post(url, json=payload)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f'Error: {e}')
return None
# Example usage
fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
result = analyze_position(fen, depth=15)
if result:
print(f\"Best move: {result['best_move']}\")
print(f\"Ponder: {result['ponder']}\")
for eval in result['evaluations']:
print(f\"Depth {eval['depth']}: {eval['score_cp']}\")
Node.js (axios)
Async/Await with axios
const axios = require('axios');
async function analyzePosition(fen, options = {}) {
const { depth = 15, multipv = 1, time = 1000 } = options;
const response = await axios.post(
'https://stockfish-api.didi.web.id/api/v1/analyze',
{ fen, depth, multipv, time },
{ headers: { 'Content-Type': 'application/json' } }
);
return response.data;
}
// Usage example
(async () => {
try {
const fen = 'r3k2r/ppp2ppp/2n5/3qp3/2B1P3/2N2N2/PPPP1PPP/R1BQK2R w KQkq - 0 5';
const result = await analyzePosition(fen, { depth: 12, multipv: 3 });
console.log('Best move:', result.best_move);
console.log('Ponder:', result.ponder);
result.evaluations.forEach(e => {
console.log(`Depth ${e.depth}: CP ${e.score.cp}`);
});
} catch (error) {
console.error('Error:', error.message);
}
})();
WebSocket Real-time Analysis
JavaScript WebSocket Client
// Connect to WebSocket for real-time analysis
const wsUrl = 'wss://stockfish-api.didi.web.id/ws';
const socket = new WebSocket(wsUrl);
socket.onopen = () => {
console.log('Connected to Stockfish WebSocket');
// Send analysis request
const request = {
type: 'analyze',
fen: 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1',
depth: 15
};
socket.send(JSON.stringify(request));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'analysis') {
console.log('Best move:', data.best_move);
console.log('Evaluation:', data.evaluation);
}
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
};
socket.onclose = () => {
console.log('WebSocket connection closed');
};
Error Handling
Handling API Errors
// JavaScript example with comprehensive error handling
async function fetchAnalysis(fen, options = {}) {
const url = 'https://stockfish-api.didi.web.id/api/v1/analyze';
try {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ fen, ...options })
});
if (!response.ok) {
// Handle different error types
switch (response.status) {
case 400:
throw new Error('Invalid FEN notation or missing parameters');
case 429:
throw new Error('Rate limit exceeded. Please try again later.');
case 500:
throw new Error('Server error. Please try again.');
default:
throw new Error(`HTTP error! Status: ${response.status}`);
}
}
return await response.json();
} catch (error) {
if (error instanceof TypeError) {
console.error('Network error:', error.message);
}
throw error;
}
}
// Usage with try-catch
try {
const result = await fetchAnalysis('invalid-fen');
} catch (error) {
console.error('Analysis failed:', error.message);
}