Python 10: Working with APIs and Web Data

🎯 Goal:

By the end of this lesson, you’ll be able to:

  • Understand what an API is
  • Use Python to send GET requests
  • Handle JSON responses
  • Pull real-time data (like weather, stock prices, etc.)

1. What Is an API?

An API (Application Programming Interface) is a way for your code to talk to another system or service.
Instead of scraping websites, you ask the website:

“Can you give me this data in a clean format?”

They respond with structured data, usually in JSON format.


2. Installing the requests Library

You’ll use requests to connect to APIs:

pip install requests

Then import it in your code:

import requests

3. Fetch Data from a Public API

Example: Get weather from the Open-Meteo API (no key required)

url = "https://api.open-meteo.com/v1/forecast?latitude=51.05&longitude=-114.07&current_weather=true"
response = requests.get(url)

# Check if it worked
print(response.status_code)  # 200 means OK

4. Working with JSON

Convert the response to a dictionary:

data = response.json()
print(data)

# Access nested values
temperature = data["current_weather"]["temperature"]
windspeed = data["current_weather"]["windspeed"]
print(f"Current temp: {temperature}°C, Wind: {windspeed} km/h")

5. Example: Build a Simple Weather Reporter

def get_weather(lat, lon):
    url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&current_weather=true"
    r = requests.get(url)
    if r.status_code == 200:
        data = r.json()
        temp = data["current_weather"]["temperature"]
        wind = data["current_weather"]["windspeed"]
        return f"Temperature: {temp}°C | Wind: {wind} km/h"
    else:
        return "Failed to fetch data."

print(get_weather(51.05, -114.07)) 

6. Handling Errors

Always wrap your API calls with try-except:

try:
    response = requests.get(url)
    response.raise_for_status()  # raises error for bad response
except requests.exceptions.RequestException as e:
    print("API error:", e)

7. Practice Time

Try these in your blog_env:

  • Use an API to get exchange rates (hint: exchangerate.host or currencyapi.com)
  • Get a random joke from https://official-joke-api.appspot.com/random_joke
  • Print the joke’s setup and punchline
  • Save JSON data to a file
  • Load it back using json.load()

✅ Summary

  • APIs are how you get real-time data (weather, news, prices)
  • requests.get() sends a call; .json() lets you work with the result
  • Handle errors with try-except for reliability
  • Real-world: pull product data, crypto prices, delivery ETAs — anything!

Comments

Leave a comment