1.02 – API Basics | AI Course

🔌 1.02 – API Basics

📑 On this page

🌐 What is an API?

📌 Definition

API (Application Programming Interface) is a set of rules that allows different software applications to communicate with each other. Think of it as a waiter in a restaurant – you give an order (request), the waiter takes it to the kitchen (API), and brings back your food (response).

💡 Why APIs matter for AI

When you use ChatGPT, you're actually using an API behind the scenes. Your prompts are sent to OpenAI's servers, processed by GPT-4, and the response comes back. You don't need to run the model on your computer!

📡 REST APIs

📌 REST (Representational State Transfer)

Most AI APIs use REST architecture. Key concepts:

MethodUse with AI APIsExample
GETRetrieve model info, check usageGET /v1/models
POSTSend prompts, get completionsPOST /v1/chat/completions

🔐 Authentication

📌 API Keys

Most AI APIs require an API key – a unique secret string that identifies you and tracks your usage.

# Example API key header
Authorization: Bearer sk-xxxxxxxxxxxxxxxxxxxxxxxx
⚠️ Security Warning
  • Never share your API key
  • Never commit it to GitHub
  • Use environment variables instead of hardcoding
  • Rotate keys periodically

📞 Making Your First API Call

📌 OpenAI API Example (Chat Completion)
cURL (command line) example:
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "gpt-4",
    "messages": [{"role": "user", "content": "What is an LLM?"}],
    "temperature": 0.7
  }'
Python example:
from openai import OpenAI

client = OpenAI(api_key="YOUR_API_KEY")

response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "What is an LLM?"}],
    temperature=0.7
)

print(response.choices[0].message.content)
JavaScript (Node.js) example:
import OpenAI from 'openai';

const openai = new OpenAI({ apiKey: 'YOUR_API_KEY' });

async function main() {
  const completion = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: 'What is an LLM?' }],
    temperature: 0.7,
  });
  console.log(completion.choices[0].message.content);
}
main();

💰 Rate Limits & Pricing

📌 Key Concepts
ModelInput Price (per 1M tokens)Output Price (per 1M tokens)
GPT-4 Turbo$10.00$30.00
GPT-3.5 Turbo$0.50$1.50
Claude 3 Sonnet$3.00$15.00
Claude 3 Haiku$0.25$1.25

✍️ Exercises

Exercise 1.02.1 – Understanding API responses

What would be the HTTP status code for each situation?

  1. Your API call succeeds and returns data
  2. Your API key is invalid
  3. You hit your rate limit (too many requests)
  4. The API endpoint doesn't exist
Answers:
1. 200 OK
2. 401 Unauthorized
3. 429 Too Many Requests
4. 404 Not Found
Exercise 1.02.2 – API key security

List three security best practices for handling API keys.

Answers:
1. Use environment variables (.env files) – never hardcode keys
2. Add your .env file to .gitignore
3. Rotate keys regularly and use different keys for development/production
4. Use API key restrictions (IP whitelisting or allowed endpoints when available)
Exercise 1.02.3 – Try it yourself

Sign up for a free API key from OpenAI, Anthropic, or Google and make your first API call. What response did you get?

Setup Tips:
- OpenAI: platform.openai.com → Sign up → API keys → Create new key
- Start with $5 free credit (new users)
- Run the Python example above after installing `pip install openai`
- Save your key as an environment variable to keep it secure
📌 Key Takeaways
📘 Next Module: 1.03 – Prompt Engineering →