How to build a trivia game with an API

A trivia game needs three things: good questions, a fair way to show them, and a way to keep score. Here’s how to put them together with TriviaAPI.

1. Get a key

Make a free account and create a key. While you build, you can also use the demo key demo (up to 5 questions a request).

2. Ask for a round of questions

Ask for a whole round at once, with the categories and difficulty you want:

const res = await fetch("https://triviaapi.games/v1/questions?amount=10&category=movies,music-80s&difficulty=medium",
  { headers: { "X-API-Key": "YOUR_KEY" } });
const { questions } = await res.json();

3. Shuffle the answers

Each question has one correct_answer and three incorrect_answers. Put them together and shuffle, so the right answer isn’t always in the same place:

function shuffled(q) {
  const all = [...q.incorrect_answers, q.correct_answer];
  for (let i = all.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [all[i], all[j]] = [all[j], all[i]]; }
  return all;
}

4. Keep score

Compare the player’s choice with correct_answer. To reward speed, give more points for a faster right answer, for example 1,000 points at the start of the clock down to 500 at the end.

5. Avoid repeats

Every question has a stable id. Save the ids each player has seen, and skip them when they come up again.

6. Keep your key private

Call the API from your server, not from a public web page, so nobody can copy your key. Then send the questions to your players.

Where to go next