---
# System prepended metadata

title: 06 - API Calls

---

# 06 - API Calls

**Notebook:** `06-api-calls.ipynb`

## Video

<iframe width="720" height="406" src="https://www.youtube.com/embed/cZpNESJEOZ8?si=lSryI7uuNfOyZAkU" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

---

## What is an API Call?

An **API call** lets your code talk to external services like OpenAI. Instead of typing into ChatGPT manually, your code can send questions and receive answers programmatically.

This is where things get exciting—we're about to connect to the same AI that powers ChatGPT, but from our own code!

---

## Colab Setup: API Keys

Before we can use OpenAI, you need to set up your API key. This is only going to work if you have created an OpenAI API key in your secrets.

1. Click the little **key icon** in the sidebar
2. Click **"Add new secret"**
3. Name it exactly: `OPENAI_API_KEY`
4. Paste in the secret value we've sent you

### Why Keep It Secret?

We do NOT want to put that value in our actual code. If our code gets shared, other people will have that API key and they can spend money on our account.

So it's very important we keep these secret. There are always ways of holding onto API keys that don't expose them to the world outside of our development team:

- In GitHub, we do special stuff
- In Colab, we store secrets in the **Secrets area**

```python
from google.colab import userdata
import os

os.environ["OPENAI_API_KEY"] = userdata.get("OPENAI_API_KEY")
```

---

## Importing OpenAI

The first thing we're gonna do is bring in the OpenAI package. OpenAI has worked really hard on a whole bunch of code that makes it easier for us to use their tools, and we want to build on that.

```python
from openai import OpenAI

client = OpenAI()
```

When we instantiate a client, we're now connected to OpenAI and can send requests out to it.

---

## Making Your First API Call

```python
response = client.responses.create(
    model="gpt-5-mini",
    input="What bird appears in Poe's famous poem? One sentence."
)

print(response.output_text)
```

Let's break this down:

- `response` is a variable storing the output of a function
- `client.responses.create` — this uses [**dot notation**](/glossary/coding-basics-py/dot-notation), where we use periods to access things inside an object. The `client` object has a `responses` property, which has a `create` method (a function it can run)
- `model` — which AI model to use
- `input` — the question we're asking

### A Quick Word on Dot Notation

You'll see dots everywhere from now on. It's how we access things inside objects:

```python
client.responses.create(...)   # Call a method
response.output_text           # Access a property
```

Think of it like navigating folders: `client` → `responses` → `create`. Each dot goes one level deeper.

When you press play, it takes a second because it has to send this out to OpenAI and wait for the response back.

---

## Creating a Reusable Function

Let's use what we learned about functions to make this easier. We don't want to remember that complicated syntax every time:

```python
def ask(question):
    response = client.responses.create(
        model="gpt-5-mini",
        input=question
    )
    return response.output_text

# Now we can use it simply:
print(ask("What bird is in Keats' Ode to a Nightingale? One sentence."))
```

Output: "The poem features a nightingale."

See how we wrapped up the complexity into a simple `ask()` function? Now we can ask any question with just one line!

---

## Looping Through Multiple Questions

As always, we want to think about how we would **loop** to get many possible responses:

```python
poems = ["The Raven", "Ode to a Nightingale", "The Windhover"]

for poem in poems:
    answer = ask(f"What bird appears in {poem}? One sentence.")
    print(answer)
```

This is where the **scale** starts to matter. Imagine having 100 poems—you wouldn't want to type 100 questions into ChatGPT manually!

---

## Try It: Combine What You've Learned

Things you could try:

- Start with one of those earlier more complex arrays of poems (with title, author, etc.)
- Send off one of those properties to OpenAI
- Look for an additional property of the poem and assign it
- Ask for "the most appropriate image prompt" for instance

**Remember:** If you hit any problems—something's not working or there's a line you don't understand—**ask Gemini**. It's right there. Just copy, paste the line in and ask for help until you feel like you understand what the code is doing.

---

## Summary

In this notebook, you learned:

- **API calls** let your code talk to external services
- Keep your **API key secret** using Colab's Secrets feature
- The OpenAI **client** lets you send requests to GPT models
- You can wrap API calls in **functions** for easy reuse
- **Looping** through API calls lets you process many items at scale

Next up: **structured output** — getting predictable data back from AI!