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 Method | Purpose |
|---|---|
| GET | Retrieve data from the server |
| POST | Send new data to the server |
| PUT | Update existing data completely |
| PATCH | Update part of existing data |
| DELETE | Remove data from the server |
The requests library is Python's most popular tool for making HTTP calls to APIs — simple, readable, and beginner-friendly.
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 dictAPI responses are almost always JSON — which converts directly into a Python dictionary or list, letting you extract exactly the fields you need.
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"])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.
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")| Status Code | Meaning |
|---|---|
| 200 | OK - request succeeded |
| 201 | Created - new resource successfully created |
| 400 | Bad Request - something wrong with your request |
| 401 | Unauthorized - missing or invalid API key |
| 404 | Not Found - the resource doesn't exist |
| 429 | Too Many Requests - rate limit exceeded |
| 500 | Internal Server Error - problem on the server's side |
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")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']}")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.
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?
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.
Use this space to write down key points, doubts, and your own examples from today's session.