Select a Subtopic
Day 11: Working with APIs
In **Day 11**, you will learn how to interact with APIs (Application Programming Interfaces) using Python. APIs allow different software applications to communicate with each other.
1. Introduction to APIs
An **API** is a set of rules that allows different software programs to communicate. In simple terms, APIs define the methods and data formats that applications use to talk to each other.
- RESTful APIs are commonly used, and they work over HTTP (or HTTPS).
- JSON (JavaScript Object Notation) is the most common data format returned by APIs.
- APIs can fetch weather data, retrieve stock prices, and much more.
2. Using `requests` Library in Python
Python provides a simple way to make HTTP requests with the `requests` library. You can easily fetch data from an API endpoint using GET requests.
Installation:
pip install requests
Basic API Request (GET method):
1
2
3
4
5
6
7
8
9
import requests
url = 'https://jsonplaceholder.typicode.com/posts'
response = requests.get(url)
if response.status_code == 200:
print("Request was successful.")
else:
print(f"Failed to fetch data. Status code: {response.status_code}")
3. Handling JSON Responses
Most APIs return data in **JSON format**. To work with this data in Python, you need to parse it into Python dictionaries or lists.
1
2
3
4
5
6
7
import requests
url = 'https://jsonplaceholder.typicode.com/posts'
response = requests.get(url)
data = response.json()
print(data[:3]) # Print the first 3 posts
4. Practical API Example: Fetching Data from OpenWeatherMap
Now let's use a real API. We'll fetch data from a public API called **OpenWeatherMap** to get weather information for a given city.
Step 1: Get an API Key
1. Visit OpenWeatherMap and create an account to generate an API key.
Step 2: Use the API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import requests
api_key = 'your_api_key'
city = 'London'
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
weather = data['weather'][0]['description']
temperature = data['main']['temp'] - 273.15 # Convert Kelvin to Celsius
print(f"Weather in {city}: {weather}")
print(f"Temperature: {temperature:.2f}°C")
else:
print(f"Failed to get weather data. Status code: {response.status_code}")
Exercises:
- Fetch and display data from a public API: Choose any free API and fetch data using the `requests` library.
- API Error Handling: Update the weather API script to handle error codes (e.g., city not found, invalid API key).
- Write a function to call the OpenWeather API: Create a function `get_weather(city)` that fetches weather data and returns the weather description and temperature.
By the end of **Day 11**, you should be comfortable with:
- Understanding and working with APIs.
- Fetching and processing data from APIs.
- Error handling in API requests.