π What is an API?
An API (Application Programming Interface) is a contract between programs. One program (the server) offers a service β "give me weather," "check this account balance," "process this payment" β and your code (the client) asks for it. The server responds with data (usually JSON).
Think of it like a restaurant: you (client) don't cook. You call the kitchen (server) with an order, and the chef returns a meal. APIs work the same way. Your Python script doesn't calculate currency rates β it asks an API, which does the heavy lifting and returns the answer.
Every API call is an HTTP request: a GET (fetch data), POST (send data), PUT (update), or DELETE (remove). The server responds with a status (200 = success, 404 = not found, 500 = error) and a body (usually JSON).
π The HTTP Request/Response Dance
β‘ Why APIs Matter
Every production system talks to APIs. PayPal processes payments via APIs. Weather apps fetch forecasts via APIs. LLMs like ChatGPT accept queries and return completions via APIs. If you want to build anything at scale β fintech, e-commerce, AI integration β you will use APIs.
In AI/ML: Every model serving infrastructure uses APIs. Your Python script trains a classifier, saves it, and then serves predictions to a web API. The frontend calls that API with new data, gets predictions back. Same dance β HTTP request, JSON response.
π The Business Scenario
Arjun, a Hyderabad-based developer, is building a side project for Jumia Kenya sellers. They list prices in KSh but often need to know the value in INR for inventory planning. He decides to build a converter that hits a free forex API every hour, stores rates, and displays them. No files to manage β just HTTP calls and JSON parsing.
π» Step 1: Your First GET Request
Start simple: fetch JSON from a public API with no authentication. We'll use a free forex API endpoint.
π» Step 2: Add Query Parameters & Headers
Many APIs accept parameters (like ?currency=USD&limit=10) and require headers (like API keys). Here we pass parameters to request a specific currency conversion and add a custom User-Agent header.
π» Step 3: Parse Complex JSON & Handle Nested Data
Real APIs return nested JSON with many fields. Use dict navigation to extract what you need, handle missing keys gracefully.
π» Step 4: POST Requests with JSON Payloads
GET fetches. POST sends data (form data, JSON, files). Use json= parameter to send a dict as JSON automatically.
π» Step 5: Error Handling, Timeouts & Rate Limits
Real APIs fail, timeout, and enforce rate limits. Always use try/except, set timeouts (so your code doesn't hang forever), and check status codes.
β οΈ Common Pitfalls
if response.status_code == 200 before parsing JSON. A 500 error returns HTML error page, not JSON. Parsing it crashes.api_key = os.getenv('API_KEY'). Commit .env to .gitignore.requests.get(url) hangs forever if the server is down. Always pass timeout=5.time.sleep(2)π APIs in the Real World
Where you'll use this
π€ The AI Connection
How LLMs & APIs Go Together
Every LLM interaction is an API call. When you use ChatGPT, you send text via the OpenAI API, get back completions. When you embed models in your app, you serve them via APIs β your frontend calls your backend, which calls your model inference API, returns predictions as JSON.
Example: A spam classifier. Train it in Jupyter, save it, wrap it in a Flask API, call it from Python: requests.post() β model runs β JSON response. That's production AI.
π Your Challenge
Fetch currency rates for three currencies (KES, INR, USD, GBP β pick 3) from a free API, catch any errors, and print them with currency symbols. Hint: use the exchangerate-api.com endpoint from Step 1, with a 5-second timeout.
requests.get() with a list of currencies. Loop through the rates dict. Try to make your code handle errors (status != 200, timeout, etc).
π€ Interview Questions
π Quick Quiz
π API Cheatsheet
| Concept | Code | Example / Notes |
|---|---|---|
| Basic GET | requests.get(url) |
Fetch data. Returns response object with .json(), .text, .status_code |
| GET with params | requests.get(url, params={...}) |
params={'q': 'python'} β ?q=python |
| GET with headers | requests.get(url, headers={...}) |
headers={'User-Agent': 'MyApp/1.0'} |
| POST data | requests.post(url, json=data) |
Sends dict as JSON. Use data= for form-encoded |
| Parse JSON | response.json() |
Converts JSON string to Python dict |
| Get nested value | data.get('key', default) |
Safe. Returns default if key missing |
| Check status | response.status_code == 200 |
200=OK, 201=Created, 404=NotFound, 500=Error |
| Timeout | requests.get(url, timeout=5) |
Raise Timeout exception after 5 sec |
| Raise for errors | response.raise_for_status() |
Raises HTTPError for 4xx/5xx |
| Auth (API key) | headers={'Authorization': 'Bearer KEY'} |
Include key in Authorization header |
β Key Takeaways
- APIs are contracts between programs. You send HTTP requests (GET, POST, etc.), servers return JSON responses.
- Use
requests.get()for reading,requests.post()for sending. Always check status codes and handle errors. - JSON parsing is crucial: use
.get()for nested navigation, never assume a key exists, wrap in try/except. - Authentication via API keys is standard. Never hardcode keys β use environment variables. Rotate if exposed.
- Real-world APIs enforce rate limits (429), timeout connections (use timeout=5), and fail unpredictably. Always add retry logic and logging.
Ready to apply APIs in production?
Join the Best AI Program: The AI-Era Analyst β 5 months, fully online, with placement assistance. Week 1 is free.
Explore The AI-Era Analyst β