Building Your First API Tool ๐Ÿ”Œ

Class 9Age 13โ€“14Lesson 11 of 12๐Ÿ†“ Free
Student in Pune working in Google Colab on a laptop, Python code calling an AI API visible on screen, modern co-working space
Watch first - 2-3 minutes

Class 9 Lesson 11 - Building Your First API Tool

No sign-in needed - English narration - Safe for all school ages

Meet Dev โ€” Class 9, Pune

Dev's school has a WhatsApp group where students post questions about homework. One evening he thought: "What if I could build a simple bot that automatically answers basic science questions?" His older cousin, a software developer, said: "Easy โ€” use the Gemini API. You don't need to train any AI. You call Google's AI through an API, and it does all the work."

In 40 minutes, Dev had a Python script running in Colab that could answer any science question by calling the Gemini API. He learned something powerful: you don't need to build AI to use AI. APIs let you connect to the world's most powerful models with 5 lines of code. Today you'll build the same.

Concept
What Is an API?

An API (Application Programming Interface) is a way for one program to talk to another program over the internet. It's like a waiter in a restaurant: you (your code) place an order โ†’ the waiter (API) takes it to the kitchen (the server) โ†’ returns with your food (the response).

๐Ÿ’ป
Your Code
Python script in Colab
โ†’
๐Ÿ“ก
HTTP Request
POST with prompt + API key
โ†’
๐Ÿค–
Gemini AI Server
Google's infrastructure
โ†’
๐Ÿ“‹
JSON Response
Text answer in your code
Part 1
Understanding JSON Responses

When you call an API, the response comes back as JSON. Here's what a Gemini API response looks like:

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Photosynthesis is the process by which plants use sunlight, water and carbon dioxide to produce glucose and oxygen."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 12,
    "candidatesTokenCount": 28
  }
}

To extract just the answer text from Python: response['candidates'][0]['content']['parts'][0]['text']

Security โ€” Read Carefully
API Key Safety Rules
โŒ NEVER Do This
API_KEY = "AIzaSyXXXXXXXXXXXX"
Hardcoding your API key in code you share on GitHub, Colab, or WhatsApp will expose it. Bots scrape GitHub in seconds. Your account will be billed or suspended.
โœ… Do This Instead
import os
API_KEY = os.environ.get("GEMINI_KEY")
Store your key as an environment variable or in Colab Secrets (๐Ÿ”‘ icon). The code can be shared safely โ€” the key stays private.
Real risk: Exposed API keys are automatically scraped by bots within minutes. Google will revoke your key and may charge for any usage made by attackers. This is a real cost to real people. Protect your keys like passwords.
Part 2
Build a Science Q&A Tool with Gemini API
# Science Q&A Tool using Google Gemini API
# Run this in Google Colab
# 1. Get your free API key at: https://aistudio.google.com/app/apikey
# 2. In Colab: click the ๐Ÿ”‘ icon (Secrets), add GEMINI_KEY = your_key

import google.generativeai as genai
import os

# โ”€โ”€ Step 1: Configure API key from environment โ”€โ”€
# In Colab Secrets: name=GEMINI_KEY, value=your_actual_key
from google.colab import userdata
API_KEY = userdata.get('GEMINI_KEY')

genai.configure(api_key=API_KEY)

# โ”€โ”€ Step 2: Choose a model โ”€โ”€
model = genai.GenerativeModel('gemini-1.5-flash')  # fast, free tier

# โ”€โ”€ Step 3: Create a system prompt โ”€โ”€
SYSTEM_PROMPT = """You are a helpful science tutor for Class 9 students in India.
Answer questions clearly and concisely in simple English.
Use real Indian examples where possible.
Maximum 4 sentences per answer."""

def ask_science_question(question):
    """Send a science question to Gemini and return the answer."""
    try:
        full_prompt = f"{SYSTEM_PROMPT}\n\nStudent question: {question}"
        response = model.generate_content(full_prompt)
        return response.text
    except Exception as e:
        return f"Error: {e}. Check your API key and internet connection."

# โ”€โ”€ Step 4: Interactive Q&A loop โ”€โ”€
print("๐Ÿ”ฌ Science Q&A Tutor (powered by Gemini AI)")
print("Type 'quit' to exit\n")

questions = [
    "What is photosynthesis and why is it important?",
    "Explain Newton's second law with a cricket ball example.",
    "How does a vaccine work in simple terms?"
]

for q in questions:
    print(f"Q: {q}")
    answer = ask_science_question(q)
    print(f"A: {answer}")
    print("-" * 60)

# โ”€โ”€ Step 5: Interactive mode โ”€โ”€
print("\nYour turn! Ask your own question:")
while True:
    user_q = input("Question (or 'quit'): ").strip()
    if user_q.lower() == 'quit':
        print("Goodbye!")
        break
    if len(user_q) < 5:
        print("Please ask a proper question.")
        continue
    print(f"Gemini: {ask_science_question(user_q)}\n")
Rate limits: The free Gemini API tier allows about 60 requests per minute and 1 million tokens per day. For a school project or hobby tool, this is plenty. If you hit a 429 error, wait 60 seconds and retry.
Part 3
Extend It: Add Error Handling
import time

def ask_with_retry(question, max_retries=3):
    """Call the API with basic retry logic for rate limit errors."""
    for attempt in range(max_retries):
        try:
            full_prompt = f"{SYSTEM_PROMPT}\n\nQuestion: {question}"
            response = model.generate_content(full_prompt)
            return response.text

        except Exception as e:
            error_str = str(e)
            if '429' in error_str:
                wait_time = 2 ** attempt  # exponential backoff: 1s, 2s, 4s
                print(f"Rate limited. Waiting {wait_time}s before retry...")
                time.sleep(wait_time)
            elif '403' in error_str:
                return "API key error โ€” check your key in Colab Secrets."
            elif '400' in error_str:
                return "Bad request โ€” your question may contain blocked content."
            else:
                return f"Unexpected error: {error_str}"

    return "Max retries reached. Try again in a minute."

# Test it
print(ask_with_retry("How do earthquakes happen? Explain for a Class 9 student."))
What you just built: A production-quality pattern used in real AI applications. Exponential backoff (waiting 1s, 2s, 4s between retries) is the standard way to handle rate limits without overwhelming a server.

๐Ÿงช Check Your Understanding โ€” Lesson 11 Quiz

1. What does API stand for and what does it do?
a) Automated Python Intelligence โ€” runs Python faster
b) Application Programming Interface โ€” a way for programs to communicate with each other over the internet
c) Artificial Processing Interface โ€” makes AI models faster
d) Advanced Program Installation โ€” installs libraries automatically
2. In a REST API, a POST request is used to:
a) Retrieve (fetch) data from the server
b) Delete data on the server
c) Send data to the server (like sending a prompt to the AI)
d) Update the server software
3. What is JSON used for in API communication?
a) A programming language used to write APIs
b) A structured text format (like a Python dictionary) used to send and receive data between your code and the API server
c) A security protocol for encrypting API keys
d) A type of machine learning model
4. Why should you NEVER hardcode your API key directly in your Python code?
a) Python doesn't allow string variables to store API keys
b) It makes the code run slower
c) If you share the code (GitHub, Colab, WhatsApp), the key becomes public and attackers can use it to generate costs or block your account
d) API providers automatically rotate keys every hour
5. In Colab, the correct way to store your API key safely is:
a) Write it in a comment above the import line
b) Save it in a text file in the same folder
c) Use Colab Secrets (๐Ÿ”‘ icon) and access it with userdata.get()
d) Print it at the start of each cell to confirm it's loaded
6. A 429 error from the Gemini API means:
a) Your question contained harmful content
b) The API key is invalid or expired
c) You have exceeded the rate limit โ€” too many requests in a short time. Wait and retry.
d) The server is permanently down
7. In the ask_with_retry() function, "exponential backoff" means:
a) Increasing the quality of prompts on each retry
b) Waiting for exponentially increasing time between retries (1s, 2s, 4s) to avoid overloading the server
c) Sending the request to multiple servers simultaneously
d) Reducing the length of the prompt on each retry
8. The SYSTEM_PROMPT in the Q&A tool is used to:
a) Authenticate with the API server
b) Define the AI's role, audience, and constraints so all responses follow the same style
c) Configure the Python environment
d) Set the maximum number of tokens the API will return
โ† Lesson 10: AI in the Workplace Lesson 12: Capstone Project โ†’