⚡0 XP🔥0

Using AI APIs with Python

Lesson 17 of 19 ⏱ 8 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs Python

Call AI models from your own Python programs - API keys, the Claude and OpenAI Python SDKs, system prompts, temperature, max tokens, batch processing, error handling, retries and cost control.

Why use an API?#

Chat apps are great for one-off tasks. But to automate work - generate 500 report-card comments, classify 2,000 support emails, build a website chatbot - you call the AI model from your own program through an API (Application Programming Interface).

Your Python program  →  sends prompt (HTTPS)  →  AI provider's servers
                     ←  returns response      ←
हिंदी में समझें

API के ज़रिए आपका Python program सीधे AI model से बात कर सकता है - बिना chat window खोले। इससे आप automation कर सकते हैं: जैसे 500 students के लिए अलग-अलग comments, 2000 emails की categories, या अपनी website पर chatbot।

ध्यान रखें:

  • API पैसे लेती है (tokens के हिसाब से) - इसलिए खर्च पर नज़र रखें।
  • API key एक password की तरह है - इसे कभी code में, GitHub पर या किसी को share न करें।

Step 1: Get an API key#

  1. Create an account on the provider's developer platform (for example, the Claude Console for Anthropic, or the OpenAI Platform).
  2. Add billing / credits.
  3. Create an API key - a secret string that identifies you.
Common Mistake

An API key is like a password linked to your money. Anyone with it can use your credits.

  • Never paste it in code you share, screenshots, or public GitHub repos.
  • Store it in an environment variable.
  • If a key leaks, delete it in the dashboard immediately and create a new one.

Set it as an environment variable:

# Windows (PowerShell) - new terminals will see it
setx ANTHROPIC_API_KEY "your-key-here"
setx OPENAI_API_KEY "your-key-here"

# macOS / Linux
export ANTHROPIC_API_KEY="your-key-here"

Or use a .env file with the python-dotenv package (and add .env to .gitignore).

Step 2: Install the SDK#

pip install anthropic      # for Claude
pip install openai         # for OpenAI models

Step 3: Your first API call#

Claude (Anthropic)#

from anthropic import Anthropic

client = Anthropic()   # reads ANTHROPIC_API_KEY from the environment

message = client.messages.create(
    model="claude-sonnet-5-5",          # check the docs for current model names
    max_tokens=500,
    system="You are a friendly Python trainer. Use simple English.",
    messages=[
        {"role": "user", "content": "Explain list comprehensions in 5 lines."}
    ],
)
print(message.content[0].text)

OpenAI#

from openai import OpenAI

client = OpenAI()      # reads OPENAI_API_KEY from the environment

response = client.responses.create(
    model="gpt-5.5",                    # check the docs for current model names
    instructions="You are a friendly Python trainer. Use simple English.",
    input="Explain list comprehensions in 5 lines.",
)
print(response.output_text)

The structure is the same everywhere: model + system instructions + user message(s) → text reply. Everything you learned about prompts applies directly.

Did you know?

Model names change as providers release new versions. Always check the provider's documentation (docs.claude.com, platform.openai.com) for the current model list and prices. The API code on this page needs your own computer and key - it won't run in the browser editor.

Important parameters#

Parameter What it does Typical value
model which model to use bigger = smarter but costlier; smaller = faster and cheaper
max_tokens maximum reply length 300-2000
system / instructions the system prompt role, rules, format
messages / input the conversation list of user/assistant turns
temperature randomness (where supported) 0-0.3 for extraction, 0.7+ for creative work

A reusable helper function#

Wrap the API call in one function so the rest of your program stays simple:

import time
from anthropic import Anthropic

client = Anthropic()
MODEL = "claude-sonnet-5-5"

def ask_ai(prompt, system="You are a helpful assistant.", max_tokens=800, retries=3):
    for attempt in range(retries):
        try:
            msg = client.messages.create(
                model=MODEL,
                max_tokens=max_tokens,
                system=system,
                messages=[{"role": "user", "content": prompt}],
            )
            return msg.content[0].text
        except Exception as e:              # rate limit, network error, etc.
            if attempt == retries - 1:
                raise
            wait = 2 ** attempt             # 1s, 2s, 4s ... exponential backoff
            print(f"Error: {e}. Retrying in {wait}s")
            time.sleep(wait)

Batch processing: one prompt per row#

Combine templates (previous lesson) with the API to process a whole spreadsheet:

import csv

TEMPLATE = ("Write a 2-sentence encouraging progress comment for {name}, a {course} "
            "student. Attendance {attendance}%, last test {score}/100. "
            "Mention one strength and one next step.")

with open("students.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))

for row in rows:
    row["comment"] = ask_ai(TEMPLATE.format(**row),
                            system="You are a supportive teacher. Plain text only.",
                            max_tokens=150)
    print(row["name"], "done")

with open("students_with_comments.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=rows[0].keys())
    writer.writeheader()
    writer.writerows(rows)

Try the same flow here with a fake ask_ai (so it runs in the browser without a key):

▶ Try it YourselfPython
Ctrl + Enter to run

Getting structured data back#

Ask for JSON and parse it (as in the Output Formats lesson). Many providers also offer structured outputs / tool use features that return guaranteed JSON matching a schema - use them in production apps.

import json

prompt = """Extract details from this enquiry and return only JSON with keys:
name, phone, course_interest, preferred_batch (morning/evening/weekend/unknown).

<enquiry>Hi I'm Karan, 98xxxxxx21, want to join python, evenings are best</enquiry>"""

reply = ask_ai(prompt, system="Return only valid JSON. No extra text.")
data = json.loads(reply[reply.find("{"): reply.rfind("}") + 1])
print(data["course_interest"])

Controlling cost#

Providers charge per million tokens, separately for input and output (output usually costs more).

▶ Try it YourselfPython
Ctrl + Enter to run

Cost-saving tips:

  • Use a smaller model for simple tasks (classification, extraction).
  • Keep prompts focused; don't resend huge documents unnecessarily.
  • Set a sensible max_tokens.
  • Test on 5-10 rows before running 5,000.
  • Set a monthly spending limit in the provider dashboard.

Handling errors#

Error Meaning Action
Authentication (401) wrong / missing key check the environment variable
Rate limit (429) too many requests wait and retry with backoff
Server overloaded (5xx) provider busy retry later
Bad request (400) invalid parameters / too long fix the request

Summary#

  • APIs let your programs use AI for automation and apps.
  • Keep API keys in environment variables - never in code or Git.
  • Install the SDK, then call client.messages.create(...) (Claude) or client.responses.create(...) (OpenAI) with a model, system prompt and messages.
  • Wrap calls in a helper with retries; combine with templates for batch work.
  • Watch costs: tokens × price; test small, choose the right model, set limits.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Estimate the cost

Write cost_rupees(input_tokens, output_tokens, in_price, out_price, usd_to_inr) where prices are US dollars per million tokens. Return the total cost in rupees rounded to 2 decimals.

2

Retry with backoff

Write call_with_retry(func, retries=3) that calls func() and returns its result. If it raises an exception, try again, up to retries attempts in total. If every attempt fails, re-raise the last exception. (Don't sleep in this exercise.)

Quick Quiz

Q1.

Where should you store your API key?

Q2.

What does the max_tokens setting control?

Q3.

An API call fails with a rate-limit error. What should your program do?

Q4.

How are API calls usually charged?

Q5.

Why use a low temperature for data extraction?