Your First AI API Call
Connect Python to a real AI model. Make your first API call and see how AI tools work behind the scenes.
Every time you use ChatGPT, Gemini, or any other AI tool, your device sends a message to a server somewhere, and that server sends back a response. That back-and-forth communication happens through something called an API.
In this lesson, you're going to do what those apps do -- but directly, with Python code.
What's an API?
API stands for Application Programming Interface. Think of it like a restaurant:
- You (the customer) don't go into the kitchen to cook your food
- You tell the waiter (the API) what you want
- The waiter takes your order to the kitchen (the AI model)
- The kitchen makes your food (processes your request)
- The waiter brings it back to you (returns the response)
An API is the waiter. It's the middleman that lets your code talk to AI models without needing to understand everything happening behind the scenes.
Why APIs Matter
Understanding APIs is a career skill that's in high demand. Every modern software system uses APIs. When a job posting says "API experience," this is what they mean -- knowing how to send requests and handle responses.
Even if you never become a full-time developer, understanding APIs helps you:
- Automate tasks that would take hours manually
- Connect different tools together
- Build custom solutions for your workplace
- Understand how the digital world actually works
Setting Up: Google's Gemini API
We'll use Google's Gemini API because it has a generous free tier. Here's how to get your API key:
- Go to aistudio.google.com
- Sign in with your Google account
- Click "Get API Key" in the left sidebar
- Click "Create API Key"
- Copy the key -- you'll need it in a moment
Important: Your API key is like a password. Don't share it publicly, don't post it on social media, and don't include it in files you share with others.
Your First API Call
Open Google Colab and create a new notebook. First, install the library we need:
!pip install google-generativeai
The ! at the beginning tells Colab to run this as a system command, not Python code.
Now let's make our first call:
import google.generativeai as genai
# Replace with your actual API key
genai.configure(api_key="YOUR_API_KEY_HERE")
# Choose the model
model = genai.GenerativeModel("gemini-pro")
# Send a message and get a response
response = model.generate_content("What are three good career fields in San Antonio, Texas?")
print(response.text)
Run that cell. You just made an AI API call. The same thing ChatGPT's interface does when you hit "send" -- you just did it with four lines of Python.
Making It Interactive
Let's build something more useful -- an interactive AI assistant:
import google.generativeai as genai
genai.configure(api_key="YOUR_API_KEY_HERE")
model = genai.GenerativeModel("gemini-pro")
# Get user's question
question = input("Ask an AI question: ")
# Add context to make it relevant
prompt = f"""Answer this question in a helpful, simple way.
Keep the answer under 100 words.
Consider the perspective of someone in San Antonio, Texas.
Question: {question}"""
response = model.generate_content(prompt)
print(f"\nAI Response:\n{response.text}")
Notice what we did there. We didn't just send the user's raw question -- we wrapped it in a prompt that gave the AI instructions about how to respond. This is prompt engineering in code.
Building a Practical Tool
Let's build something genuinely useful -- a job description analyzer:
import google.generativeai as genai
genai.configure(api_key="YOUR_API_KEY_HERE")
model = genai.GenerativeModel("gemini-pro")
job_description = input("Paste a job description (or a few sentences about a job): ")
prompt = f"""Analyze this job description and provide:
1. The top 3 skills required
2. Whether AI knowledge would be helpful for this role (yes/no and why)
3. One free online resource to learn the most important skill
Job Description: {job_description}
Format your response with clear headers and keep it concise."""
response = model.generate_content(prompt)
print(f"\n--- Job Analysis ---\n{response.text}")
This is a tool that could genuinely help someone in a job search. You built it with about 10 lines of code.
Understanding the Response
When the API sends back a response, it's not just text. It includes metadata -- information about the response:
import google.generativeai as genai
genai.configure(api_key="YOUR_API_KEY_HERE")
model = genai.GenerativeModel("gemini-pro")
response = model.generate_content("Explain APIs in one sentence.")
# The text of the response
print("Response:", response.text)
# Safety ratings (how the AI evaluated its own response)
print("\nSafety ratings:", response.candidates[0].safety_ratings)
The safety ratings show you that AI models are constantly evaluating their own outputs -- checking for harmful content, bias, and other issues. This connects back to what you learned in Module 5 about AI ethics.
Error Handling
Sometimes API calls fail. Maybe the internet is down, or you hit a rate limit, or your key expired. Good code handles these situations:
import google.generativeai as genai
genai.configure(api_key="YOUR_API_KEY_HERE")
model = genai.GenerativeModel("gemini-pro")
try:
response = model.generate_content("What is Python?")
print(response.text)
except Exception as e:
print(f"Something went wrong: {e}")
print("Check your API key and internet connection.")
The try/except block says: "Try this code. If something goes wrong, don't crash -- run this other code instead." Professional developers use this pattern everywhere.
Limits and Keys
Two things to understand about APIs:
- Rate limits stop you from sending too many requests too fast. The learning limits are more than enough for this course. Do not put an API call inside a loop that runs thousands of times.
- Your API key is like a password. Anyone who has it can use your account. Never paste it into a shared document, a public notebook, a screenshot, or a chat.
Age note: Many AI developer accounts require you to be 18 or older. If you are younger, work with a parent, guardian, or instructor, or practice with the in-browser code playground instead.
API key safety
0 of 4 doneWhat You Just Learned
Take a step back and appreciate what you did in this lesson:
- You got an API key from a major tech company
- You installed a Python library
- You connected to an AI model programmatically
- You sent prompts and received responses
- You built a practical tool
- You handled errors like a professional
That's not "beginner stuff." That's real development work. People get hired for exactly these skills.
Try This
Build a "Community Helper" chatbot. Use a loop so the user can ask multiple questions (type "quit" to exit). Add a system prompt that tells the AI to focus on resources available in San Antonio. Bonus: save the conversation to a list so you can print the full chat history at the end.
Talk About It
Now that you've seen what happens behind the scenes when you use AI, does it feel less mysterious and more like a tool? How does understanding the "how" change the way you think about AI?
Go deeper: Machine Learning, Minus the Hype, a Temerarii Media playbook by Dom Davis.