🌐 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.

requests.get(url) β†’ response β†’ response.json()

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

GET
Fetch data
Request: "Give me the latest rate for INR/USD"
POST
Create/send data
Request: "Process this β‚Ή1000 M-Pesa payment"
PUT
Update data
Request: "Update my profile to Hyderabad"
DELETE
Remove data
Request: "Remove this API key"

⚑ 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

πŸš€
Fintech Β· Arjun's Side Project
Building a Currency Converter for Jumia Kenya

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.

5
API verbs
3
Status codes
1KSh
Query param

πŸ’» 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.

fetch_exchange_rate.py β–Ά Run to see output below
# Output Status: 200 1 KSh = 0.6125 β‚Ή

πŸ’» 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.

fetch_with_headers.py β–Ά Parameters & headers
# Output 1 KSh β†’ 0.6125 β‚Ή 1 KSh β†’ 0.0077 $ 1 KSh β†’ 0.0061 Β£

πŸ’» 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.

parse_json_safely.py β–Ά Nested JSON handling
# Output πŸ“¦ requests πŸ‘€ By psf ⭐ 51,840 stars πŸ”€ Language: Python

πŸ’» 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.

send_data_with_post.py β–Ά Sending JSON data
# Output (example) Status: 201 βœ… Transaction TXN-2024-5501 sent Amount: 5000 KSh

πŸ’» 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.

robust_api_call.py β–Ά Production-ready error handling
# Output βœ… 1 KSh = 0.6125 β‚Ή

⚠️ Common Pitfalls

Ignoring Status Codes
if response.status_code == 200 before parsing JSON. A 500 error returns HTML error page, not JSON. Parsing it crashes.
API Keys in Code
Never hardcode keys. Use environment variables: api_key = os.getenv('API_KEY'). Commit .env to .gitignore.
No Timeout
requests.get(url) hangs forever if the server is down. Always pass timeout=5.
Ignoring Rate Limits
Status 429 means "slow down." Most free APIs limit to 100 calls/hour. Add delay between calls: time.sleep(2)

🌍 APIs in the Real World

Where you'll use this

πŸ’³
Fintech β†’ Stripe, Razorpay, M-Pesa APIs
Process payments, check balances, refund transactions programmatically
πŸ›’
E-commerce β†’ Shopify, Jumia APIs
Sync inventory, fetch orders, update pricing from your code
πŸ—ΊοΈ
Geolocation β†’ Google Maps, OpenWeatherMap APIs
Get coordinates, forecast weather, route optimization
πŸ“Š
Data β†’ Stock APIs, crypto exchanges
Fetch real-time prices, build dashboards, run backtests
πŸ€–
AI β†’ OpenAI, Hugging Face APIs
Generate text, translate, classify via hosted models
πŸ“±
Social β†’ Twitter, GitHub APIs
Post tweets, fetch user data, trigger CI/CD pipelines

πŸ€– 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.

Use 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

GET fetches data from the server (read-only, safe to repeat, parameters in URL). POST sends data to the server (creates/updates, should not repeat without thinking, data in body). GET is idempotent; POST is not.
429 = Too Many Requests. The API is rate-limiting you. Handling: check for 429, back off (add delay), retry after a few seconds. Use exponential backoff for retries (2s, 4s, 8s…).
If you commit code with keys to GitHub, anyone can see them. They can impersonate you, drain your API quota, or rack up charges. Use environment variables or a secrets manager. Rotate keys immediately if exposed.
API returns 500 error (HTML page, not JSON). response.json() crashes. Solution: (1) check status first, (2) use response.json(strict=False) to be lenient, (3) wrap in try/except. Always validate structure: use data.get('key', default) not data['key'].
Use a wrapper function that: (1) sets timeout, (2) catches Timeout/ConnectionError exceptions, (3) checks status code, (4) raises HTTPError for 4xx/5xx, (5) returns None or raises custom exception on failure. Optionally, add retry logic with exponential backoff for transient errors (timeout, 5xx). Log errors. Return structured response (success bool, data, error message) so caller knows what happened.

πŸ“ Quick Quiz

Question 1 of 5
What does the status code 200 indicate?
Question 2 of 5
Which library in Python is used to make HTTP requests?
Question 3 of 5
What is the difference between GET and POST?
Question 4 of 5
What does response.json() do?
Question 5 of 5
If an API returns a 429 status code, what should you do?
5
/ 5
Excellent!

πŸ“‹ 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.
Africa & India's Best AI Academy
πŸ€– AI-first πŸŽ“ Placement Assistance

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 β†’