Perfect — thanks for clarifying. Let’s build this from the ground up, starting with what APIs are, why they exist, and how we use them in Python. I’ll keep it thorough and structured but also student-friendly, so learners without prior HTTP or environment variable knowledge can follow smoothly.
🌐 APIs in Python — Beginner’s Guide (PC & Mac, Cursor + uv)
Part 1 — What is an API, really?
API = Application Programming Interface.
- Think of it as a menu in a restaurant.
- You (the client) don’t walk into the kitchen. You read the menu, choose what you want, and the waiter (API call) takes your request to the kitchen (server). The kitchen returns your meal (response).
- APIs let software talk to software in a structured way.
APIs on the web
Most modern APIs use the web (HTTP) for communication. Your code sends a request to a server; the server sends back a response.
- Example: Weather apps use weather APIs. They send a request: “What’s the weather in Delhi today?” The server sends back a structured response: “25°C, cloudy”.
- Without APIs, every app would need to build its own weather database — impossible. APIs let services reuse and share.
Part 2 — HTTP basics: Request and Response
When you load a webpage, your browser secretly does this:
- Request: your browser sends an HTTP request to a server.
- Response: the server replies with data (HTML, JSON, etc.).
Two common request types:
- GET → ask for something (like “give me today’s weather”).
- POST → send something (like “store this new blog post”).
Both go to a specific endpoint (a URL like https://api.example.com/v1/weather
).
You can think of endpoints as doors to different services.
Part 3 — JSON: the language of API data
When two computers talk, they need a simple shared format.
That’s JSON (JavaScript Object Notation).
- Looks like Python dictionaries/lists.
- Works in nearly all programming languages.
- Lightweight and easy for humans to read.
Example JSON response:
{
"city": "Delhi",
"temperature": 25,
"conditions": ["cloudy", "humid"]
}
In Python, JSON is automatically parsed into dict
/list
:
import json
data = '{"city":"Delhi","temperature":25}'
obj = json.loads(data) # parse string -> Python dict
print(obj["city"]) # "Delhi"
Part 4 — Why APIs use keys (API Keys)
APIs are valuable. Providers don’t want random strangers abusing them.
API Key = a secret password for your program.
- Identifies who is calling.
- Enforces limits (e.g., 1000 requests per day).
- Allows billing (if paid).
Best practices:
- Never paste the key directly into your code (dangerous if shared on GitHub).
- Instead, store it safely in an environment variable.
Part 5 — Environment variables (keeping secrets safe)
An environment variable is a hidden note your operating system keeps for a program.
Example: Instead of writing
API_KEY = "12345-SECRET"
we put it into a hidden file called .env
:
MY_API_KEY=12345-SECRET
Then in Python:
import os
from dotenv import load_dotenv
load_dotenv() # read .env file
API_KEY = os.getenv("MY_API_KEY")
print(API_KEY)
This way, you can share your code without sharing your secret keys.
(And yes: always add .env
to .gitignore
!)
Part 6 — Client libraries (why they exist)
You could call APIs with raw HTTP (requests.get/post
), but it’s messy: you need to build headers, JSON, authentication manually.
Client libraries = helper packages.
- Provided by API companies.
- Wrap raw HTTP in friendly Python functions.
- Example: Instead of
requests.post("https://api.openai.com/v1/chat/completions", headers=..., body=...)
, you just do:openai = OpenAI() response = openai.chat.completions.create(model="gpt-4o-mini", messages=messages)
Much simpler!
Part 7 — Typical steps to use any API
- Sign up on the provider’s website.
- Read the docs to find which endpoint does what.
- Get your API key (secret).
- Store key in
.env
(MY_KEY=abc123
). - Install their library with
uv add <package>
. - Import library in Python and make a call.
- Use the result (JSON, text, object).
Part 8 — Example 1: OpenAI API (Chat)
Setup
uv add openai python-dotenv
.env
OPENAI_API_KEY=sk-xxxx...
Python code
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
openai = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
messages = [
{"role": "system", "content": "You are a teacher."},
{"role": "user", "content": "Explain gravity in simple terms."}
]
resp = openai.chat.completions.create(model="gpt-4o-mini", messages=messages)
print(resp.choices[0].message.content)
Part 9 — Example 2: Send an Email with SendGrid
Setup
uv add sendgrid python-dotenv
.env
SENDGRID_API_KEY=SG.xxxxx...
Python code
import os
from dotenv import load_dotenv
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
load_dotenv()
sg = SendGridAPIClient(os.getenv("SENDGRID_API_KEY"))
message = Mail(
from_email="you@example.com",
to_emails="friend@example.com",
subject="Hello from my API app",
html_content="<strong>This email was sent via Python!</strong>"
)
response = sg.send(message)
print(response.status_code) # 202 means accepted
Part 10 — Debugging and best practices
- Check status codes:
200 OK
→ success401 Unauthorized
→ wrong/missing key429 Too Many Requests
→ slow down500+
→ server issues, try again later
- Never share your
.env
file. - Start with docs examples; modify gradually.
- Test small: call a “hello world” endpoint first before bigger integrations.
✅ With this, students now know:
- What APIs are and why they exist,
- Basics of HTTP requests/responses,
- JSON as the standard data format,
- API keys and environment variables for security,
- How client libraries simplify life,
- The standard workflow to use any API,
- Two practical examples (OpenAI chat + SendGrid email).