A Magic 8 Ball is the perfect first API project. The whole program is one idea — ask a question, get an answer — so you can focus on the part that matters: sending a request and doing something with the response. In this tutorial you will build the same Magic 8 Ball three times: as a web page in plain JavaScript, as a Python script in your terminal, and as a one-line chat command for Twitch. All three call the same free API. There is no sign-up and no API key, so you can paste the code and run it right now.
Open the API docs and playground →Try a live request in your browser before writing a single line of code.What You Will Build
- Version 1, a web page: one HTML file with a black ball, a question box and a Shake button. About 50 lines including the styling. Open it in any browser.
- Version 2, a terminal app: about 10 lines of Python that keep answering until you press Enter on an empty line.
- Version 3, a chat command: a single line that gives a Twitch channel its own !8ball command, with no code to host.
If you have never called an API before, start with Version 1. If you already know fetch, skim it and jump to whichever version you need.
The API in One Request
Everything below talks to one endpoint. Paste this into a terminal, or paste just the URL into your browser's address bar:
curl "https://yesnooracle.app/api/oracle?tool=magic-8-ball"You get back a small JSON object like this one:
{
"answer": "yes",
"verdict": "yes",
"word": "It is certain",
"phrase": "No doubt about it — the ball is sure.",
"tool": "magic-8-ball",
"forced": false,
"image": "https://yesnooracle.app/art-magic8.webp"
}What the fields mean
- word is the answer you show, in the toy's voice: “It is certain”, “Ask again later”, “Very doubtful”.
- phrase is one extra sentence to go with it.
- answer is the verdict boiled down to yes, no or maybe, handy if you want to color the result green or red.
- image is artwork you can display if you want a picture.
Three parameters worth knowing
- tool picks the voice. Use magic-8-ball for this project. Other values include tarot (it draws a card), pendulum, crystal-ball and i-ching; the API docs list all eight.
- force fixes the verdict to yes, no or maybe. You will want this when you test how your page looks for each kind of answer.
- format=text returns one plain line instead of JSON. That is what makes Version 3 possible.
curl "https://yesnooracle.app/api/oracle?tool=magic-8-ball&force=no"Version 1: A Magic 8 Ball Web Page
Save this as magic8.html and open it in your browser. It works straight from your desktop. You do not need a server, because the API allows requests from any website or file.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Magic 8 Ball</title>
<style>
body { margin: 0; min-height: 100vh; display: grid; place-items: center;
background: #0f0a22; color: #e8e3f5; font-family: system-ui, sans-serif; }
.ball { width: 220px; height: 220px; border-radius: 50%; background: #111;
display: grid; place-items: center; margin: 0 auto 24px;
box-shadow: inset -18px -18px 40px #000, 0 0 40px #4b3f8a; }
.window { width: 120px; height: 120px; border-radius: 50%; background: #1d2a8f;
display: grid; place-items: center; text-align: center;
padding: 12px; box-sizing: border-box; font-size: 14px; }
</style>
</head>
<body>
<main>
<div class="ball"><div class="window" id="answer">Ask a question</div></div>
<form id="ask">
<input id="question" placeholder="Will it rain tomorrow?" required>
<button>Shake</button>
</form>
<p id="phrase"></p>
</main>
<script>
const API = "https://yesnooracle.app/api/oracle?tool=magic-8-ball";
document.getElementById("ask").addEventListener("submit", async (event) => {
event.preventDefault(); // keep the page from reloading
const answer = document.getElementById("answer");
const phrase = document.getElementById("phrase");
answer.textContent = "...";
try {
const res = await fetch(API);
if (!res.ok) throw new Error("HTTP " + res.status);
const data = await res.json();
answer.textContent = data.word; // e.g. "It is certain"
phrase.textContent = data.phrase; // one line in the ball's voice
} catch (err) {
answer.textContent = "Reply hazy";
phrase.textContent = "Could not reach the oracle. Try again.";
}
});
</script>
</body>
</html>How the code works
- The form's submit event fires when someone presses Shake or hits Enter. event.preventDefault() stops the browser from reloading the page, which is what a form does by default.
- fetch(API) sends the request. await waits for the reply without freezing the page. MDN's guide to the Fetch API covers everything else fetch can do.
- res.ok is true only for a successful response. A common beginner bug is skipping this check: fetch does not throw on errors like a 429 “too many requests”, so you have to check yourself.
- res.json() turns the response into an object, and the answer goes onto the page with textContent. Prefer it over innerHTML for anything that comes from a server, because textContent never interprets HTML.
- If anything fails, the catch block shows “Reply hazy”, which is a real Magic 8 Ball answer.
Calling an API on another domain from a web page only works when that server allows it, a browser rule called CORS. This API sends Access-Control-Allow-Origin: *, which allows every site. That is why the file works without a backend. Many free APIs do not do this, which is the source of the “blocked by CORS policy” error new developers run into.
Why the API never sees your question
You may notice the code never sends the question anywhere. That is not a shortcut. It is how the toy works. A real Magic 8 Ball is a 20-sided die floating in dark blue liquid, and it shows whichever face floats up, whatever you asked. We take apart the plastic version in how a Magic 8 Ball works. The question box exists for the person asking, and asking out loud is half the fun.
“Ten of the twenty answers are a yes. Whatever you build, it will be an optimist half the time.”
Version 2: A Python Magic 8 Ball in the Terminal
The same idea in Python, using the Requests library (pip install requests). Save it as magic8.py:
import requests
API = "https://yesnooracle.app/api/oracle"
while True:
question = input("Ask the Magic 8 Ball (Enter to quit): ").strip()
if not question:
break
r = requests.get(API, params={"tool": "magic-8-ball"}, timeout=10)
r.raise_for_status()
data = r.json()
print(data["word"] + ".", data["phrase"])$ python magic8.py
Ask the Magic 8 Ball (Enter to quit): Should I learn Rust next?
Outlook good. What's ahead looks bright.A few details worth copying into your own projects:
- params= builds the query string for you, so you never glue question marks and ampersands together by hand.
- timeout=10 stops the script from hanging forever if the network drops. Requests has no timeout by default.
- raise_for_status() turns an HTTP error into a Python exception. It is the Python version of the res.ok check above.
Need questions to test with? Our list of Magic 8 Ball questions to ask has more than two hundred.
Version 3: A !8ball Command for Twitch Chat
Chat bots like Nightbot and StreamElements can call a URL and post whatever comes back. Adding format=text makes the API return one plain line, so a Magic 8 Ball for your channel is a single command. A moderator types it once in chat:
!commands add !8ball $(urlfetch https://yesnooracle.app/api/oracle?tool=magic-8-ball&format=text)!command add !8ball $(customapi https://yesnooracle.app/api/oracle?tool=magic-8-ball&format=text)From then on anyone in chat can type !8ball and get an answer such as “Outlook good. What's ahead looks bright.” The syntax comes straight from Nightbot's urlfetch docs and StreamElements' customapi docs. Both bots cut responses at about 400 characters, and every answer here is far shorter than that. Swap magic-8-ball for tarot to draw a card instead, or for pendulum, which answers in a dowser's voice. Our guide to how to use a pendulum explains what that means.
See the finished Magic 8 Ball →Our own version runs on this same API — ask it something before you build yours.Ideas to Take It Further
- A voice picker. Add a <select> with the eight tool values and put the chosen one into the URL.
- Show the art. Set an <img>'s src to the image field.
- A history list. Keep the last five answers in an array and save it to localStorage so it survives a reload.
- Color by verdict. Use the answer field to make yes answers green and no answers red.
- A shake animation. Add a CSS class with a short wobble on submit and remove it when the answer arrives.
- A Discord bot. When someone types !8ball, fetch the format=text URL and reply with the text. It is the same request as Version 3, with your bot doing the posting.
- Tests. Use force=yes and force=no so every test run gets the answer it expects.
Limits and Fair Use
The API is free for personal and commercial projects. To keep it fast for everyone there is a soft limit per IP address: about 60 requests a minute for JSON, and 600 a minute with format=text, because chat bots share servers. If you hit the limit you get a 429 response. That is the error the res.ok check catches. A machine-readable description lives at /openapi.json, which tools like Postman can import. If you publish something you built, a link back is appreciated but never required.
One honest note: the answers are random. That is the point of a Magic 8 Ball, and it makes a fun first project, but it is not a way to make real decisions about health, money or the law.
Frequently Asked Questions
- Is there a free Magic 8 Ball API?
- Yes. A GET request to https://yesnooracle.app/api/oracle?tool=magic-8-ball returns one of the toy's 20 classic answers as JSON. It is free, needs no sign-up or API key, and accepts requests from any website.
- Do I need an API key?
- No. There is nothing to register. The only limit is a soft one per IP address: about 60 requests a minute, or 600 a minute in plain-text mode.
- How do I add a Magic 8 Ball command to Twitch chat?
- With Nightbot, a moderator types: !commands add !8ball $(urlfetch https://yesnooracle.app/api/oracle?tool=magic-8-ball&format=text). StreamElements works the same way with $(customapi …). The format=text option returns one short line that fits the bots' 400-character limit.
- How many answers does a Magic 8 Ball have?
- Twenty: ten positive, five non-committal and five negative. The API's magic-8-ball voice draws from the same twenty, so about half of its answers are a yes.
Sources
- Using the Fetch API — MDN — how fetch sends requests and why it does not throw on HTTP errors.
- Cross-Origin Resource Sharing (CORS) — MDN — the browser rule behind Access-Control-Allow-Origin.
- Node.textContent — MDN — why textContent is safer than innerHTML for text from a server.
- Requests quickstart — params, timeouts and raise_for_status in the Python library.
- Nightbot urlfetch variable — the command syntax and the 400-character limit for plain-text responses.
- StreamElements customapi variable — the equivalent StreamElements syntax.
- Magic 8 Ball — Wikipedia — the toy's 20 answers and their 10 / 5 / 5 split.
