Yes or No Oracle

Build a Magic 8 Ball With a Free API: JavaScript, Python and a Twitch Command

By Published
Build a Magic 8 Ball With a Free API: JavaScript, Python and a Twitch Command

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

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:

Terminal
curl "https://yesnooracle.app/api/oracle?tool=magic-8-ball"

You get back a small JSON object like this one:

Response
{
  "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

Three parameters worth knowing

Force a 'no' while testing
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.

magic8.html
<!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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.”

The classic toy splits its answers 10 positive, 5 non-committal and 5 negative. The API's magic-8-ball voice uses the same twenty.

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:

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"])
Example run
$ 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:

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:

Nightbot
!commands add !8ball $(urlfetch https://yesnooracle.app/api/oracle?tool=magic-8-ball&format=text)
StreamElements
!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

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