Tutorials
How to build a quiz site where players pick a tag
Use the tag registry to let players search and browse more than a thousand tags, pick one and play a quiz on it. With the API calls in curl, fetch and the TypeScript SDK.
Categories are fine for a general quiz, but most people would rather play one on something they care about: the Beatles, the 1960s, Formula One, France. Every question in The Trivia API has tags like that, from a fixed list of 1,047.
This tutorial builds a site where the player searches or browses those tags, picks one and gets a quiz on it. It sticks to the API calls and the logic around them, so you can use whichever framework you like.
The finished example is a React and Vite app: play it here, or read the code on GitHub. The quiz screens (the questions and the results) are the same as in the React quiz tutorial, so this page doesn't repeat them.
What you'll build
Two requests do all the work:
GET /v2/tag-registryonce, when the page loads, to get every tag with its name, description and question count, in the player's languageGET /v2/questions?tags=<slug>when the player picks one
Everything in between (searching, grouping, hiding tags that are too small for a quiz) happens in the browser, on the list you already have.
The tag registry
/v2/tag-registry lists every tag, sorted by slug. It's public, so you don't need a key:
curl "https://the-trivia-api.com/v2/tag-registry"[
{
"slug": "animal:african-wildlife",
"label": { "en": "African wildlife" },
"description": {
"en": "Elephants, giraffes, hippos and the other animals that live in the wild across Africa."
},
"count": 13
},
{
"slug": "animal:amphibians",
"label": { "en": "Amphibians" },
"description": {
"en": "Frogs, toads, newts and salamanders: how they live, breed and change as they grow."
},
"count": 5
}
]Each tag has:
| Field | What it is |
|---|---|
slug | What you pass to tags=, e.g. place:france. It doesn't change. |
label | A name to show the player, keyed by language code |
description | A sentence about what the tag covers, keyed by language code |
count | How many questions you can get with this tag |
In other languages
Add language to get the labels and descriptions in another language. The registry supports en (the default), es, nl, hi, tr, fr, de, ru and pt, and you don't need a key for any of them:
curl "https://the-trivia-api.com/v2/tag-registry?language=fr"[
{
"slug": "animal:african-wildlife",
"label": { "fr": "Faune africaine" },
"description": {
"fr": "Éléphants, girafes, hippopotames et autres animaux sauvages vivant en Afrique."
},
"count": 13
},
{
"slug": "animal:amphibians",
"label": { "fr": "Amphibiens" },
"description": {
"fr": "Grenouilles, crapauds, tritons et salamandres : leur mode de vie, leur reproduction et leur développement."
},
"count": 5
}
]label and description come back only in the language you asked for, never in all of them. If a tag doesn't have that language, you get its English text under en instead. Any other value of language gets a 400 listing the supported codes. The slugs and counts are the same in every language.
The SDK doesn't have a function for the registry yet, so use plain fetch. The example app throws the SDK's ApiError when it fails, so errors from the registry and the questions can be handled in one place, and it sorts the tags by count so the biggest come first:
import { ApiError } from "@trivia-api/sdk";
type LocalisedText = Partial<Record<string, string>>;
export type RegistryTag = {
slug: string;
label?: LocalisedText;
description?: LocalisedText;
count: number;
};
const REGISTRY_URL = "https://the-trivia-api.com/v2/tag-registry";
export const fetchTagRegistry = async (language = "en"): Promise<RegistryTag[]> => {
const response = await fetch(`${REGISTRY_URL}?${new URLSearchParams({ language })}`);
if (!response.ok) {
throw new ApiError(response.status, await response.text(), response.statusText);
}
const tags: RegistryTag[] = await response.json();
return tags.sort((a, b) => b.count - a.count);
};Fetch it when the page loads and keep it for the session, rather than once per click. If the player switches language, fetch it again with the new one.
Sending an API key is optional. If you do send one, the request uses one of your key's credits, the same as /v2/questions/count.
Showing the label and description
label and description are objects keyed by language code, holding just the language you asked for. Read that language, fall back to English for a tag that came back in English, and fall back to the slug if there's no label at all:
export const tagLabel = (tag: RegistryTag, language = "en") =>
tag.label?.[language] ?? tag.label?.en ?? tag.slug;
export const tagDescription = (tag: RegistryTag, language = "en") =>
tag.description?.[language] ?? tag.description?.en ?? "";Grouping by prefix
Every slug is a prefix, a colon and a name. The prefix says what kind of thing the tag is, which is how place:jordan (the country) and person:michael-jordan (the basketball player) can both exist. It also makes a good filter for a long list. There are 13 prefixes:
| Prefix | Group | Example |
|---|---|---|
category | Categories | category:geography |
topic | Topics | topic:mythology |
music | Music | music:the-beatles |
place | Places | place:france |
person | People | person:napoleon-bonaparte |
work | Films, TV, books and games | work:middle-earth |
event | Events | event:world-war-ii |
sport | Sport | sport:football-soccer |
science | Science | science:space-exploration |
food | Food and drink | food:cocktails |
era | Eras | era:1960s |
org | Organisations | org:european-union |
animal | Animals | animal:dinosaurs |
The category tags are the API's 10 categories, written with hyphens (category:sport-and-leisure), so a tag picker can do a category picker's job too.
In code, the group is a lookup on whatever comes before the colon. The example app puts anything it doesn't recognise in "Other", in case a new prefix turns up:
const GROUPS: Record<string, string> = {
category: "Categories",
topic: "Topics",
music: "Music",
place: "Places",
person: "People",
work: "Films, TV, books and games",
event: "Events",
sport: "Sport",
science: "Science",
food: "Food and drink",
era: "Eras",
org: "Organisations",
animal: "Animals",
};
export const groupOf = (slug: string) => {
const prefix = slug.split(":")[0];
return Object.hasOwn(GROUPS, prefix) ? GROUPS[prefix] : "Other";
};Tags aren't nested, so a question gets both the broad and the narrow tag. A question about the Eiffel Tower has place:paris, place:france, place:europe and place:western-europe, and one about a 1969 hit has era:1960s and era:20th-century. That means every tag works on its own: place:europe gets you everything about Europe in one request, without walking a tree.
Hiding small tags
Some tags are huge and some only have a few questions. The biggest are the categories, then broad tags like topic:film (1,061 questions) and era:20th-century (1,055). At the other end, 499 of the 1,047 tags have fewer than 10 questions, and 59 have none at all.
A tag with 3 questions makes a disappointing quiz, so hide tags below the size of your quiz and let players show them if they want:
const MIN_QUESTIONS = 10;
const playable = tags.filter((tag) => tag.count >= MIN_QUESTIONS);The example app has a "Show tags with fewer than 10 questions" checkbox, and won't start a quiz from a tag with a count of 0.
count is for multiple choice (text_choice) questions unless you say otherwise. If your quiz uses other types, pass types, the same way as for /v2/questions/count:
curl "https://the-trivia-api.com/v2/tag-registry?types=text_input"With that, place:france has a count of 121 instead of 94. Counting works for every type without a subscription, though fetching text_input and image_choice questions needs a key.
Searching
With about a thousand tags in memory, search doesn't need a server. Match what the player typed against the label and description, ignoring case. The example app does this inside its TagPicker component, with a checkbox in place of the fixed minimum:
export const searchTags = (
tags: RegistryTag[],
search: string,
group = "All",
language = "en"
) => {
const query = search.trim().toLowerCase();
return tags.filter(
(tag) =>
tag.count >= MIN_QUESTIONS &&
(group === "All" || groupOf(tag.slug) === group) &&
(tagLabel(tag, language).toLowerCase().includes(query) ||
tagDescription(tag, language).toLowerCase().includes(query))
);
};Pass the language you fetched the registry in, so you search the same text you're showing the player. Searching descriptions as well as labels helps more than you'd expect. No tag is called "D-Day", but the description of event:world-war-ii mentions it, so a player searching for it still finds the right tag.
Filtering a thousand items on every keystroke is cheap. Rendering a thousand buttons isn't, especially on a phone, so the example app shows the first 50 matches and a "Show more" button.
Getting the questions
Once the player picks a tag, ask for questions with it. One tag per request:
curl "https://the-trivia-api.com/v2/questions?tags=place:france&limit=10"[
{
"category": "geography",
"id": "622a1c357cc59eab6f950007",
"correctAnswer": "France",
"incorrectAnswers": ["Andorra", "Belgium", "Luxembourg"],
"question": { "text": "In which country is Normandy?" },
"tags": ["category:geography", "place:france", "place:europe", "place:western-europe"],
"type": "text_choice",
"difficulty": "medium",
"regions": [],
"isNiche": false,
"hint": "The region lies across the English Channel from southern England and is known for its D-Day beaches.",
"explanation": "France’s Normandy region was central to the 1944 D-Day landings, which began the liberation of western Europe."
}
]With the SDK, that's getRandomQuestions:
import { getRandomQuestions } from "@trivia-api/sdk";
const questions = await getRandomQuestions({ tags: "place:france", limit: 10 });Or with fetch:
const params = new URLSearchParams({ tags: "place:france", limit: "10" });
const response = await fetch(`https://the-trivia-api.com/v2/questions?${params}`);
const questions = await response.json();You get multiple choice questions unless you ask for other types, and you get fewer than limit back if the tag doesn't have enough. That's another reason to check count first.
Slugs are case-sensitive, so send them exactly as the registry has them. Place:France gets you nothing.
Several tags means any of them
It's tempting to let players pick two tags and get questions about both. That doesn't work: several tags in one request means questions with any of them, so the quiz gets broader rather than narrower.
curl "https://the-trivia-api.com/v2/questions/count?tags=place:france" # "count": 94
curl "https://the-trivia-api.com/v2/questions/count?tags=place:france,music:rock" # "count": 390The API doesn't support asking for all of several tags. If you need it, fetch with the narrower tag and filter the tags array yourself:
const response = await fetch("https://the-trivia-api.com/v2/questions?tags=era:1960s&limit=50");
const questions = await response.json();
const sixtiesRock = questions.filter((question) => question.tags.includes("music:rock"));That only filters the questions you got back, which is 50 at most, so expect a handful: three tries gave 4, 5 and 6 of the 50. For a picker, one tag per quiz is simpler and always gives you a full quiz.
Where to go next
- The example app's code has everything on this page wired up in React, with tests. Fork it and change whatever you like.
- The filtering guide covers combining a tag with difficulties and other filters.
- Sessions stop the same question coming up twice, which matters more on small tags. They need a Regular or Complete plan.
- The API reference has every parameter for
/v2/tag-registryand/v2/questions.