API Integration
Input / Output · Implement Leaderboard API (POST/GET scores).
API Integration
What it is
The Fetch API lets JavaScript make HTTP requests to remote servers. fetch(url, options) returns a Promise that resolves to a Response object. POST requests typically include a JSON body; GET requests append parameters to the URL.
Why it matters
Modern games are connected. Leaderboards, save state, multiplayer, AI services — they all live on servers. Without API integration, the game can’t share data with anything outside the browser tab.
How GateGame implements it
The Leaderboard API uses POST to submit scores at level completion and GET to retrieve the top 10 for display. Every fetch is wrapped in a try/catch so a network failure doesn’t crash the game. The NPC AI integration uses the same pattern — POST the player’s input, receive a generated dialogue response.
Code Example
try {
const response = await fetch('/api/leaderboard', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ score, player })
});
const data = await response.json();
renderLeaderboard(data);
} catch (error) {
console.error('Leaderboard API error:', error);
showFallbackUI();
}
Key Takeaway
Fetch + JSON + try/catch is the canonical pattern. Always wrap in try/catch — the network will fail eventually.