Learn Python this summer Day 15: Working with APIs

Welcome back! Yesterday, we learned about web scraping. Today, we’ll dive into working with APIs (Application Programming Interfaces), which allow you to interact with web services and retrieve data programmatically. By the end of this day, you’ll know how to make API requests and handle responses in Python. Let’s get started!

What is an API?
An API (Application Programming Interface) is a set of rules that allows one software application to interact with another. Web APIs allow you to access and manipulate data from web services.

Making API Requests
You can use the requests library to make API requests and handle responses.

Installing the Requests Library
If you haven’t installed the requests library yet, you can do so using pip:

bash
Copy code
pip install requests
Making a GET Request
Use the requests.get() function to make a GET request to an API endpoint.

Example:

python
Copy code
import requests

url = "https://api.example.com/data"
response = requests.get(url)

print(response.status_code) # Output: 200 (if the request is successful)
print(response.json()) # Output: JSON data from the API
Handling JSON Responses
Most APIs return data in JSON format. You can use the .json() method to parse the JSON response.

Example:

python
Copy code
import requests

url = "https://api.example.com/data"
response = requests.get(url)
data = response.json()

Print specific data

print(data["key"]) # Output: Value associated with ‘key’
Making a POST Request
You can use the requests.post() function to send data to an API endpoint.

Example:

python
Copy code
import requests

url = "https://api.example.com/data"
payload = {
"key1": "value1",
"key2": "value2"
}
response = requests.post(url, json=payload)

print(response.status_code) # Output: 201 (if the request is successful)
print(response.json()) # Output: JSON data from the API
Handling API Errors
You should handle potential errors when making API requests.

Example:

python
Copy code
import requests

url = "https://api.example.com/data"
response = requests.get(url)

if response.status_code == 200:
data = response.json()
print(data)
else:
print(f"Error: {response.status_code}")
Example: Using a Public API
Let’s use a public API to retrieve data. We’ll use the OpenWeatherMap API to get the current weather for a specific city.

Sign up for a free API key at OpenWeatherMap.

Make a GET request to the API endpoint with your API key and city name.

Example:

python
Copy code
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()
temperature = data["main"]["temp"]
weather_description = data["weather"][0]["description"]
print(f"Temperature: {temperature}")
print(f"Weather: {weather_description}")
else:
print(f"Error: {response.status_code}")
Practice Time!
Let’s put what we’ve learned into practice. Write a Python program that makes an API request and processes the response.

Example: Using the OpenWeatherMap API to get the weather data for a specific city.

python
Copy code
import requests

def get_weather(city):
api_key = "YOUR_API_KEY"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    temperature = data["main"]["temp"]
    weather_description = data["weather"][0]["description"]
    print(f"Temperature in {city}: {temperature}°C")
    print(f"Weather: {weather_description}")
else:
    print(f"Error: {response.status_code}")

Get weather for a specific city

city = input("Enter city name: ")
get_weather(city)
Conclusion
Great job today! You’ve learned how to work with APIs in Python, which allows you to interact with web services and retrieve data programmatically. Tomorrow, we’ll dive into data analysis with pandas, a powerful library for data manipulation and analysis. Keep practicing and having fun coding!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *