Ravindra BagaleCourses & study guides Track your progress

Your First OpenAI and Gemini API Call in Python (Free Key Setup)

Generative AI course · Chapter 36 · Estimated reading time: 12 minutes

So far you have used AI by typing into a chat window. That works for one question at a time. But suppose you have 500 customer emails to sort, or you want your own website to answer questions. Then you need your own program to talk to the model. That is what an API is for: a doorway that lets your code send a question to ChatGPT's or Gemini's model and get the answer back as text. In this chapter you will get a Gemini API key from Google AI Studio (with a free tier), see how OpenAI's API key and billing work, make your first call in Python, build a small email classifier, and, most importantly, keep your key safe.

What you will learn in this chapter

  • What an API call is, in simple words
  • Get a Gemini API key from Google AI Studio, and what the free tier means
  • How OpenAI's API key, prepaid billing and phone check work
  • Keep the key safe in a .env file, never in your code
  • Make a hello-world call to Gemini and to OpenAI
  • Read the most common errors: wrong key and too many requests
  • Build a small email classifier

1. Suppose a coaching institute gets 200 emails a week

Suppose Kavita manages emails at a small coaching institute. Each week about 200 emails arrive: fee questions, admission enquiries, complaints and spam. She reads each one and moves it to a folder by hand.

In the chat window, she could paste one email and ask "Which category is this?". But 200 times? No. With an API, a short Python program can send each email to the model, get back one word (like fees), and sort them all while she has tea.

The model is the same one you used in the chat. The difference is who types: your program instead of you.

2. What an API call is

An API call has 4 parts:

  1. The key: a long secret text that proves who you are (like a password for your program).
  2. The model name: which model should answer, for example gemini-3.8-flash.
  3. The input: your question or instruction.
  4. The response: the answer, which your program can print, save or use.
One API call, from your code to the model and back Steps from top to bottom: 1 Key in .env, Never inside the code; 2 SDK loads the key, From the environment; 3 Send model and input, For example gemini-3.8-flash; 4 Model replies, Or an error such as 401 or 429; 5 Check the reply, Then print, save or use it. 1Key in .envNever inside the code 2SDK loads the keyFrom the environment 3Send model and inputFor example gemini-3.8-flash 4Model repliesOr an error such as 401 or 429 5Check the replyThen print, save or use it

One API call, from your code to the model and back

The SDK (software development kit) is a Python package that does the hard work for you. You write 5 lines; it handles the internet part.

pip install google-genai openai python-dotenv

3. Get your keys

Gemini (Google AI Studio) — checked on Google's pages on 19 October 2026:

  1. Go to aistudio.google.com and sign in with your Google account.
  2. Open the API keys page and create a key for a project.
  3. Copy the key once and keep it somewhere safe.

New projects start on the Free tier, with limits on requests per minute, tokens per minute and requests per day. You can see your project's exact limits in AI Studio. On the pricing page, Flash models such as gemini-3.8-flash and gemini-3.5-flash-lite are free of charge on the free tier; Pro models are paid only. Google's billing page says that on paid tiers your prompts are not used to improve Google's products. So on the free tier, never send private or customer data.

Since 28 May 2026, new keys from AI Studio are restricted to the Gemini API, and Google rejects unrestricted older-style keys for Gemini. If an old tutorial's key steps look different, follow AI Studio's current screen.

OpenAI (platform.openai.com):

  1. Create an account on platform.openai.com (this is separate from a ChatGPT subscription; a ChatGPT plan does not pay for the API).
  2. Verify your phone number; OpenAI asks for this before your first API key.
  3. Add prepaid credit in Billing. The minimum purchase is $5; credits you buy expire after 1 year. Auto-recharge is turned on by default when you buy, so turn it off if you want a fixed budget.
  4. Create a secret key in the API keys page and copy it once.

Some new accounts get a small free test allowance, but it is not guaranteed, so plan for prepaid billing.

Ravindra Bagale's Tip

The costliest beginner mistake is pasting the key straight into the code, then sharing the file or pushing it to GitHub. Automated bots scan public code for leaked keys, and someone else's usage lands on your bill or your free quota. The fix takes 2 minutes: put the key in a .env file, add .env to .gitignore, and load it with python-dotenv. If a key ever leaks, delete it in the dashboard right away and create a new one.

4. Worked example 1: keep the key safe in .env

Make a project folder with 3 files.

.env (your secret; these are dummy keys, not real ones):

OPENAI_API_KEY=sk-DUMMY-not-a-real-key-123
GEMINI_API_KEY=DUMMY-not-a-real-gemini-key

.gitignore (tells Git never to upload .env):

.env

check_key.py (prints only the first and last 4 characters):

import os
from dotenv import load_dotenv
load_dotenv()
for name in ["OPENAI_API_KEY", "GEMINI_API_KEY"]:
    key = os.getenv(name)
    if key:
        print(f"{name} loaded: {key[:4]}...{key[-4:]} ({len(key)} characters)")
    else:
        print(f"{name} is missing. Check your .env file.")

Real output (19 October 2026, with the dummy keys):

OPENAI_API_KEY loaded: sk-D...-123 (27 characters)
GEMINI_API_KEY loaded: DUMM...-key (27 characters)

Prove .env is ignored. We ran git init, git add -A and git status --short:

A  .gitignore
A  check_key.py
A  hello_gemini.py
A  hello_openai.py

.env is not in the list. That is exactly what we want.

5. Worked example 2: hello world, and reading the errors

Gemini (hello_gemini.py):

from dotenv import load_dotenv
from google import genai

load_dotenv()            # reads GEMINI_API_KEY from the .env file
client = genai.Client()  # the SDK finds the key in the environment

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Say hello to a new Python learner in one short sentence.",
)
print(response.text)

OpenAI (hello_openai.py):

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()            # reads OPENAI_API_KEY from the .env file
client = OpenAI()        # the SDK finds the key in the environment

response = client.responses.create(
    model="gpt-6-astra",
    input="Say hello to a new Python learner in one short sentence.",
)
print(response.output_text)

The model names come from each company's quickstart page on 19 October 2026. Model names change often, so if you get a "model not found" error, check the quickstart for the current name.

Expected output with a real key (yours will be similar, not the same):

Hello and welcome to Python, where every small program is a big step forward!

Real output with our dummy keys (19 October 2026, last line only; we shortened the Gemini one). You will see these errors one day, so learn them now:

OpenAI:

openai.AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-DUMMY***************-123. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401}

Gemini:

google.genai.errors.ClientError: 400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': 'API key not valid. Please pass a valid API key.', 'status': 'INVALID_ARGUMENT', ...}}

What the common errors mean:

Error Meaning Fix
401 or "API key not valid" Wrong, deleted or missing key Run check_key.py; copy the key again
429 or RESOURCE_EXHAUSTED Too many requests, or a free-tier limit was hit Wait and retry slowly; check your limits in AI Studio
Insufficient quota (OpenAI) No prepaid credit left Add credit in Billing
Model not found Old or misspelt model name Copy the name from the quickstart page

Notice that OpenAI's error hides most of the key with stars. Your own programs should do the same: never print a full key.

6. Worked example 3: an email classifier

Now Kavita's problem. We ask the model for one word only, from a fixed list, so the program can trust the answer.

from dotenv import load_dotenv
from google import genai
import time

load_dotenv()
client = genai.Client()
LABELS = ["fees", "admission", "complaint", "spam", "other"]

emails = [
    "Hello, what is the last date to pay the second fee instalment?",
    "I want to join the weekend data course. Is there a seat?",
    "The AC in room 2 has not worked for a week. Please fix it.",
    "Congratulations!!! You won a free phone, click this link now",
]

for text in emails:
    prompt = (f"Classify this email into exactly one label from {LABELS}. "
              f"Reply with the label only, in lowercase.\n\nEmail: {text}")
    reply = client.models.generate_content(model="gemini-3.8-flash", contents=prompt)
    label = reply.text.strip().lower()
    if label not in LABELS:          # never trust the model blindly
        label = "other"
    print(f"{label:<10} {text[:50]}")
    time.sleep(5)                    # stay well inside free-tier rate limits

Expected output (yours will be similar, not the same):

fees       Hello, what is the last date to pay the second fee
admission  I want to join the weekend data course. Is there a
complaint  The AC in room 2 has not worked for a week. Please
spam       Congratulations!!! You won a free phone, click thi

Three important habits in this small program:

  1. A fixed list of labels, so the answer is predictable.
  2. A check (if label not in LABELS), because a model sometimes replies "Fees." or a full sentence.
  3. A pause between calls, so you do not hit the free-tier rate limit.

Before you run it on real emails, test it on 20 made-up ones and count how many it gets right. And remember the free-tier privacy point: use made-up emails while learning.

7. What an API call costs

  • Each call uses tokens (small pieces of words) for both your input and the reply.
  • On paid tiers, you pay per million tokens; the price depends on the model. Check the live pricing page for the model you choose; prices change.
  • Short prompts, short replies ("label only") and small, fast models keep costs and limits low.
  • In the OpenAI dashboard, you can set a budget and turn off auto-recharge. In Google's console, you can watch usage for your project.

8. Beginner mistakes and quick fixes

Mistake What happens Quick fix
Key written inside the code Leaks when you share or push Use .env and .gitignore
Thinking a ChatGPT plan pays for the API API calls fail with a quota error Add API credit separately on platform.openai.com
A loop with no pause 429 errors on the free tier Add a pause; process in small batches
Trusting the reply format Program breaks on "Fees." Ask for one word and check it against a list
Sending customer data on the free tier Privacy risk Use made-up data, or a paid tier with your organisation's approval
Copying an old model name from a blog "Model not found" Use the name from the official quickstart

9. Try at home

Try at home

Task 1: set up safely

  1. Create a Gemini key in Google AI Studio.
  2. Put it in a .env file and add .env to .gitignore.
  3. Run check_key.py and confirm only 8 characters are shown.

Task 2: hello world

  1. Run hello_gemini.py with your real key.
  2. Change one letter of the key and run it again; read the error.
  3. Put the right key back.

Task 3: a classifier

  1. Write 10 made-up emails for a business you know.
  2. Run the classifier with your own label list.
  3. Count the correct labels and improve the prompt once.

Recap

In short

  1. An API lets your own program send input to a model and get the answer back.
  2. A call needs a key, a model name, the input, and code to read the response.
  3. Gemini keys come from Google AI Studio; new projects start on a free tier with rate limits.
  4. On the free tier, do not send private data; Google says paid tiers keep prompts out of product improvement.
  5. OpenAI's API needs phone verification and prepaid credit (minimum $5); a ChatGPT plan does not cover it.
  6. Keep keys in .env, ignore .env in Git, and never print a full key.
  7. 401 means a bad key; 429 means too many requests or a limit was hit.
  8. Ask for fixed, short answers and check them in code.

Make your first call this week with a free Gemini key and a .env file. Once your code can talk to a model, every repetitive text task becomes a small program.

Previous chapter: AI Coding Tools Compared: GitHub Copilot, Cursor and Claude Code

Next chapter: Embeddings Explained Simply: How AI Finds Similar Meaning


Ravindra Bagale, trainer: linkedin.com/in/ravindra-bagale. Kavita, the institute and the emails on this page are made up for learning, and the keys shown are dummy keys. Key setup, free tier, billing and model names were checked on Google's Gemini API pages and OpenAI's platform pages on 19 October 2026. The error output was produced on 19 October 2026 with dummy keys. AI output changes every time, so your output will be similar, not the same.