Ludo API Examples — Complete Working Code in Python, Node.js & cURL
This page collects working code examples for every major Ludo API operation. Each example is self-contained and ready to copy-paste into your project. All examples assume you've obtained an API key from the dashboard and have the required libraries installed. Examples are grouped by language and sorted from basic to advanced.
cURL Examples
cURL examples are the quickest way to test the API from your terminal. Replace YOUR_API_KEY with your actual key and YOUR_TOKEN with a session token from the login flow.
# Register a new player
curl -X POST "https://api.ludokingapi.site/v1/players" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"playerName": "RahulG", "deviceId": "device-001", "platform": "web"}'
# Create a private game room
curl -X POST "https://api.ludokingapi.site/v1/rooms" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"maxPlayers": 4, "gameMode": "classic", "turnTimeLimit": 30}'
# Get room details
curl -X GET "https://api.ludokingapi.site/v1/rooms/XYZ789" \
-H "Authorization: Bearer YOUR_TOKEN"
# Join a room
curl -X POST "https://api.ludokingapi.site/v1/rooms/XYZ789/join" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"playerName": "NehaK"}'
# Get player profile and stats
curl -X GET "https://api.ludokingapi.site/v1/players/plr_abc123" \
-H "Authorization: Bearer YOUR_TOKEN"
# Get leaderboard (top 50 global)
curl -X GET "https://api.ludokingapi.site/v1/leaderboards/global?perPage=50" \
-H "Authorization: Bearer YOUR_TOKEN"
# Get game history
curl -X GET "https://api.ludokingapi.site/v1/players/plr_abc123/history?perPage=10" \
-H "Authorization: Bearer YOUR_TOKEN"
Python Examples
These Python examples use the requests library. Install it with pip install requests. Each function is independent — copy just the ones you
need.
import requests
import os
BASE_URL = "https://api.ludokingapi.site/v1"
API_KEY = os.getenv("LUDO_API_KEY")
session = requests.Session()
session.headers.update({"Authorization": f"Bearer {API_KEY}"})
# --- Authentication ---
def register_player(player_name, device_id, platform="web"):
response = session.post(
f"{BASE_URL}/players",
json={"playerName": player_name, "deviceId": device_id, "platform": platform},
timeout=10
)
response.raise_for_status()
return response.json()["data"]
# --- Room Management ---
def create_room(max_players=4, game_mode="classic", turn_time_limit=30):
response = session.post(
f"{BASE_URL}/rooms",
json={"maxPlayers": max_players, "gameMode": game_mode, "turnTimeLimit": turn_time_limit},
timeout=10
)
response.raise_for_status()
return response.json()["data"]
def join_room(room_code, player_name=None):
payload = {} if player_name is None else {"playerName": player_name}
response = session.post(
f"{BASE_URL}/rooms/{room_code}/join",
json=payload,
timeout=10
)
response.raise_for_status()
return response.json()["data"]
def get_room(room_code):
response = session.get(f"{BASE_URL}/rooms/{room_code}", timeout=10)
response.raise_for_status()
return response.json()["data"]
# --- Player Data ---
def get_player(player_id):
response = session.get(f"{BASE_URL}/players/{player_id}", timeout=10)
response.raise_for_status()
return response.json()["data"]
def get_leaderboard(board_type="global", page=1, per_page=20):
response = session.get(
f"{BASE_URL}/leaderboards/{board_type}",
params={"page": page, "perPage": per_page},
timeout=10
)
response.raise_for_status()
return response.json()
# --- Quick Demo ---
if __name__ == "__main__":
player = register_player("DemoUser", "demo-device")
print(f"Registered: {player['playerId']}")
room = create_room()
print(f"Room created: {room['code']}")
leaderboard = get_leaderboard()
print(f"Top player: {leaderboard['data'][0]['playerName']}")
Node.js Examples
These Node.js examples use the built-in fetch API (Node 18+) or axios. The fetch version has no dependencies —
just paste and run.
// Ludo API Client — Node.js with native fetch (Node 18+)
const BASE_URL = 'https://api.ludokingapi.site/v1';
const API_KEY = process.env.LUDO_API_KEY;
async function apiRequest(method, endpoint, body = null, token = API_KEY) {
const options = {
method,
headers: {
'Authorization': `Bearer {token}`,
'Content-Type': 'application/json'
}
};
if (body) options.body = JSON.stringify(body);
const response = await fetch(`{BASE_URL}/{endpoint}`, options);
const json = await response.json();
if (!response.ok) {
throw new Error(`API Error: {json.error?.message || response.statusText}`);
}
return json.data;
}
// --- Player Operations ---
async function registerPlayer(playerName, deviceId, platform = 'web') {
return apiRequest('POST', 'players', { playerName, deviceId, platform });
}
async function getPlayer(playerId) {
return apiRequest('GET', `players/{playerId}`);
}
async function getLeaderboard(type = 'global', perPage = 20) {
return apiRequest('GET', `leaderboards/{type}` + `?perPage={perPage}`);
}
// --- Room Operations ---
async function createRoom(sessionToken, options = {}) {
return apiRequest(
'POST', 'rooms',
{ maxPlayers: 4, gameMode: 'classic', turnTimeLimit: 30, ...options },
sessionToken
);
}
async function joinRoom(sessionToken, roomCode) {
return apiRequest('POST', `rooms/{roomCode}/join`, {}, sessionToken);
}
// --- Demo Usage ---
(async () => {
try {
const player = await registerPlayer('NodePlayer', 'node-demo-001');
console.log('Player registered:', player.playerId);
const room = await createRoom(player.sessionToken);
console.log('Room created:', room.code);
const leaderboard = await getLeaderboard();
console.log('Top 3 players:', leaderboard[0], leaderboard[1], leaderboard[2]);
} catch (err) {
console.error(err.message);
}
})();
WebSocket Examples
WebSocket examples for real-time game events. These use the native browser WebSocket API, but the same
pattern works in Node.js with the ws library.
// Browser WebSocket — Real-time Ludo gameplay
const WS_URL = 'wss://api.ludokingapi.site/ws';
const ROOM_CODE = 'ABCD12';
const SESSION_TOKEN = 'YOUR_SESSION_TOKEN';
// Connect with token in query string
const ws = new WebSocket(`{WS_URL}?token={SESSION_TOKEN}`);
ws.addEventListener('open', () => {
console.log('WebSocket connected');
// Join the room immediately after connecting
ws.send(JSON.stringify({ type: 'room:join', roomCode: ROOM_CODE }));
});
ws.addEventListener('message', (event) => {
const msg = JSON.parse(event.data);
console.log('Event:', msg.type, msg.data || '');
switch (msg.type) {
case 'room:joined':
console.log('Joined room. Players:', msg.data.room.players);
break;
case 'game:dice-rolled':
console.log(`Player rolled {msg.data.value}`);
showDice(msg.data.value);
break;
case 'game:turn-change':
console.log(`Now it's player {msg.data.currentPlayerId}'s turn`);
updateTurnUI(msg.data.currentPlayerId);
break;
case 'game:piece-moved':
animatePiece(msg.data.pieceId, msg.data.from, msg.data.to);
break;
case 'game:ended':
console.log(`Game over! Winner: {msg.data.winnerId}`);
showResults(msg.data);
ws.close();
break;
}
});
// Actions
function rollDice() {
ws.send(JSON.stringify({ type: 'game:roll-dice', roomCode: ROOM_CODE }));
}
function movePiece(pieceId, targetPosition) {
ws.send(JSON.stringify({
type: 'game:move-piece',
roomCode: ROOM_CODE,
pieceId,
targetPosition
}));
}
Frequently Asked Questions
Yes — all REST examples work with the free tier. WebSocket examples also work, but free tier rooms expire after 4 hours and support only 2 players. To test 4-player gameplay, you'll need Starter or above. The API key from your free account dashboard works for all examples as-is.
Absolutely. The Python and Node.js examples can be adapted to React Native (use fetch for HTTP and socket.io-client
for WebSocket). For Flutter, use dio for HTTP and socket_io_client for WebSocket. The API calls themselves are
identical across all platforms.
Wrap each API call in a try/catch. Check response.ok (fetch) or
call raise_for_status() (Python requests) to surface HTTP errors.
For WebSocket, listen for the error event and implement
reconnection logic. The examples here are intentionally simple — production code should add retry
logic with exponential backoff, circuit breakers, and structured logging.
Open Chrome DevTools (F12), go to the Console tab, paste the browser WebSocket example code (adjusting the token and room code), and press Enter. You'll see console.log output for every event received. For a visual test, create a room in one browser tab and join it from another — the events will appear in both consoles.
Yes — Google Colab has Python 3 with requests pre-installed.
Create a new notebook, paste the Python example code, set your API key as an environment variable
with import os; os.environ['LUDO_API_KEY'] = 'your_key', and run.
It's an excellent way to prototype Ludo API integrations without any local setup.
Need Working Code for a Specific Feature?
Get custom Ludo API code examples tailored to your project. WhatsApp us with your requirements.
Chat on WhatsApp