SAMANTUS Python for Data Analytics — Complete Training Manual MODULE 19
← Back to Course Index

APIs


On This Page

Module 19: APIs


19.1  What is a REST API?

An API (Application Programming Interface) lets two different software systems talk to each other. A REST API is the most common type on the web — you send a request to a URL, and the server sends back data, usually in JSON format.

Think of an API like a restaurant waiter: you (the client) place an order (request), the kitchen (server) prepares it, and the waiter brings back your food (response).

HTTP MethodPurpose
GETRetrieve data from the server
POSTSend new data to the server
PUTUpdate existing data completely
PATCHUpdate part of existing data
DELETERemove data from the server

19.2  The requests Library

The requests library is Python's most popular tool for making HTTP calls to APIs — simple, readable, and beginner-friendly.

► Making a Basic GET Request
pip install requests

import requests

response = requests.get("https://api.github.com/users/octocat")
print(response.status_code)   # 200 means success
print(response.json())        # convert response to a Python dict
Output
200
{'login': 'octocat', 'id': 1, ...}

19.3  Working with JSON Responses

API responses are almost always JSON — which converts directly into a Python dictionary or list, letting you extract exactly the fields you need.

► Extracting Specific Fields
data = response.json()
print(data["login"])         # username
print(data["public_repos"])  # number of public repos

# If the API returns a list of records:
# for item in data:
#     print(item["name"])
✓ Instructor Tip
Encourage students to first print the full JSON response and study its structure before trying to extract specific fields — this avoids a lot of confusing KeyError issues.

19.4  Authentication

Many APIs require authentication to identify who is making the request — most commonly via an API key passed in the URL, headers, or as a query parameter.

► Using an API Key
import requests

API_KEY = "your_api_key_here"
url = "https://api.openweathermap.org/data/2.5/weather"
params = {"q": "Delhi", "appid": API_KEY, "units": "metric"}

response = requests.get(url, params=params)
data = response.json()
temp = data["main"]["temp"]
print(f"Temperature in Delhi: {temp}°C")
⚠ Important
NEVER hardcode API keys directly in shared or public code (like GitHub). Use environment variables or a separate config file that is excluded from version control.

19.5  Handling Errors & Status Codes

Status CodeMeaning
200OK - request succeeded
201Created - new resource successfully created
400Bad Request - something wrong with your request
401Unauthorized - missing or invalid API key
404Not Found - the resource doesn't exist
429Too Many Requests - rate limit exceeded
500Internal Server Error - problem on the server's side
► Handling API Errors Gracefully
response = requests.get(url, params=params)

if response.status_code == 200:
    data = response.json()
    print("Success:", data)
else:
    print(f"Error {response.status_code}: Could not fetch data")

19.6  Mini Project — Weather Data Fetcher

► weather_fetcher.py
import requests

def get_weather(city, api_key):
    url = "https://api.openweathermap.org/data/2.5/weather"
    params = {"q": city, "appid": api_key, "units": "metric"}
    response = requests.get(url, params=params)

    if response.status_code != 200:
        return None

    data = response.json()
    return {
        "city": city,
        "temperature": data["main"]["temp"],
        "condition": data["weather"][0]["description"]
    }

result = get_weather("Mumbai", "YOUR_API_KEY")
if result:
    print(f"{result['city']}: {result['temperature']}°C, {result['condition']}")

19.7  Practical Exercises

Basic (5 Questions)

1. Make a GET request to a free public API (e.g. https://api.github.com/users/github) and print the status code.

2. Convert an API response into a Python dictionary using .json().

3. Extract 3 specific fields from a JSON API response.

4. Print a friendly message combining 2 fields from an API response using an f-string.

5. Check if a response's status code is 200 before printing its data.

Intermediate (5 Questions)

1. Use the params argument in requests.get() to send a search query to an API.

2. Write a function that takes a city name and returns weather data from a public weather API.

3. Handle a 404 error gracefully by printing a custom 'not found' message.

4. Loop through a JSON response containing a list of items and print each one's name.

5. Save an API's JSON response directly to a local JSON file using the json module.

Advanced (5 Questions)

1. Build a 'Multi-City Weather Dashboard' that fetches and compares weather for 5 cities using a loop.

2. Fetch data from a public API and load the results directly into a Pandas DataFrame for analysis.

3. Build a function that retries a failed API request up to 3 times before giving up.

4. Combine API data with a local CSV (e.g. merge live currency exchange rates with a sales dataset).

5. Build a simple 'News Headline Fetcher' using a public news API, with graceful error handling for all status codes.

19.8  Module Quiz (MCQs)

Q1. What does API stand for?

Q2. Which HTTP method retrieves data?

Q3. Which Python library is most commonly used to call APIs?

Q4. What does status code 401 mean?

Q5. Which method converts an API response into a Python dictionary?

ℹ Answer Key
1-a, 2-b, 3-b, 4-c, 5-b

19.9  Module Assignment

Assignment: Multi-City Weather Report Builder

Expected Output: A working script that pulls live data from a real API for multiple cities and saves a clean, structured CSV report.

19.10  Interview Questions — Module 19


19.11  Student Notes Page

Use this space to write down key points, doubts, and your own examples from today's session.