Back to Blog
Working with Web APIs: Connecting Python to the Internet

Working with Web APIs: Connecting Python to the Internet

December 3, 2026
Reynov Christian

So far, all of your Python programs have worked with local data: text files, CSV tables, and JSON configs saved on your own computer. Real-world apps also talk to the internet to fetch live weather forecasts, currency exchange rates, news headlines, and stock quotes.

They do this through Web APIs. In this lesson, you will learn how HTTP requests and status codes work, how to fetch and parse live JSON data with the requests library, how to handle API keys and timeouts safely, and how to build a Real-Time Weather Dashboard App.

1. How HTTP Requests and Web APIs Work

An API (Application Programming Interface) is a structured doorway that lets one program request data from another server over HTTP. Instead of returning a colorful webpage meant for human eyes, a REST API returns clean JSON data meant for code.

Every HTTP request has four key pieces:

  • Method: GET asks a server for data (the most common method for reading APIs).
  • URL & Query Parameters: The endpoint address plus options like ?latitude=-8.65&longitude=115.22.
  • Headers: Extra metadata sent with the request, such as an API key or accepted format.
  • Status Code: A 3-digit number in the server’s reply: 200 means OK, 401 means Unauthorized, 404 means Not Found, and 500 means a Server Error.

2. Making API Calls and Parsing JSON with requests

Make sure your virtual environment from Lesson 14 is active ((.venv)) and requests is installed (python -m pip install requests). Passing query parameters via the params dictionary is much cleaner and safer than gluing strings onto a URL by hand:

import requests

url = "https://api.open-meteo.com/v1/forecast"
params = {
    "latitude": -8.65,
    "longitude": 115.22,
    "current_weather": "true",
}

response = requests.get(url, params=params, timeout=10)
response.raise_for_status()

data = response.json()
current = data["current_weather"]
print(f"Temperature: {current['temperature']} C")
print(f"Wind Speed:  {current['windspeed']} km/h")

Look at two good habits in that snippet: timeout=10 prevents your script from freezing forever if the internet drops, and response.raise_for_status() immediately raises an exception if the server returns an error code like 404 or 500. Then response.json() parses the JSON reply straight into a Python dictionary.

3. Handling API Keys Safely

Open-Meteo is free and needs no API key, which makes it ideal for learning. Many commercial APIs, however, require an API key (a secret password string) in the request headers or query parameters.

Never hardcode secret keys directly in your .py file, especially if you plan to push your code to GitHub. Instead, read them from an environment variable using os.environ.get():

import os
import requests


def fetch_protected_data(url: str) -> dict[str, object]:
    """Call an API endpoint that requires an X-API-Key header."""
    api_key = os.environ.get("MY_API_KEY")
    if not api_key:
        raise ValueError("Missing MY_API_KEY environment variable.")

    headers = {"X-API-Key": api_key}
    response = requests.get(url, headers=headers, timeout=10)
    response.raise_for_status()
    return response.json()

4. Handling Network Timeouts and Errors Gracefully

Networks fail all the time: Wi-Fi drops, servers go down, or a user types a city name that does not exist. Always wrap API calls in try and except blocks catching requests.Timeout, requests.HTTPError, and requests.RequestException so your program prints a friendly message instead of crashing with a traceback.

5. Practical Project: Real-Time Weather Dashboard App

Create a file named weather_dashboard.py inside your virtual environment workspace. This app looks up any city’s coordinates using Open-Meteo’s free Geocoding API, then fetches live temperature and wind speed from the Forecast API.

import requests

GEOCODING_URL = "https://geocoding-api.open-meteo.com/v1/search"
WEATHER_URL = "https://api.open-meteo.com/v1/forecast"


def find_city_coordinates(city: str) -> dict[str, float | str] | None:
    """Look up a city's latitude and longitude using the Geocoding API."""
    params = {"name": city, "count": 1, "language": "en", "format": "json"}
    response = requests.get(GEOCODING_URL, params=params, timeout=10)
    response.raise_for_status()

    results = response.json().get("results")
    if not results:
        return None

    top_match = results[0]
    return {
        "name": str(top_match.get("name", city)),
        "country": str(top_match.get("country", "")),
        "latitude": float(top_match["latitude"]),
        "longitude": float(top_match["longitude"]),
    }


def fetch_current_weather(latitude: float, longitude: float) -> dict[str, float | str]:
    """Fetch current temperature and wind speed for given coordinates."""
    params = {
        "latitude": latitude,
        "longitude": longitude,
        "current_weather": "true",
    }
    response = requests.get(WEATHER_URL, params=params, timeout=10)
    response.raise_for_status()

    current = response.json().get("current_weather", {})
    return {
        "temperature": float(current.get("temperature", 0.0)),
        "windspeed": float(current.get("windspeed", 0.0)),
        "time": str(current.get("time", "unknown")),
    }


def display_weather(
    location: dict[str, float | str],
    weather: dict[str, float | str],
) -> None:
    """Print a clean weather report for the user."""
    print("\n=== Live Weather Dashboard ===")
    print(f"Location:    {location['name']}, {location['country']}")
    print(f"Temperature: {weather['temperature']} C")
    print(f"Wind Speed:  {weather['windspeed']} km/h")
    print(f"Updated At:  {weather['time']} (UTC)")


def main() -> None:
    """Run the interactive Real-Time Weather Dashboard CLI."""
    print("Welcome to the Python Real-Time Weather Dashboard!")

    while True:
        city = input("\nEnter a city name (or type 'quit' to exit): ").strip()
        if not city:
            print("City name cannot be empty.")
            continue
        if city.lower() == "quit":
            print("Goodbye!")
            break

        try:
            location = find_city_coordinates(city)
            if location is None:
                print(f"Could not find a city named '{city}'. Please try again.")
                continue

            weather = fetch_current_weather(
                float(location["latitude"]),
                float(location["longitude"]),
            )
            display_weather(location, weather)
        except requests.Timeout:
            print("The weather server took too long to respond. Please try again.")
        except requests.HTTPError as error:
            print(f"The server returned an HTTP error: {error}")
        except requests.RequestException as error:
            print(f"Network error while fetching weather: {error}")


if __name__ == "__main__":
    main()

Run python weather_dashboard.py with (.venv) active and try cities like Tokyo, London, or Jakarta. Notice how cleanly the program handles unknown city names and offline connections.

Common Beginner Mistakes

  • Omitting timeout=10 in requests.get(): By default, requests has no timeout, meaning a slow server can hang your program indefinitely. Always set a timeout.
  • Forgetting response.raise_for_status(): A 404 or 500 reply does not automatically raise a Python exception. Calling raise_for_status() stops your code before it tries to parse an error page as JSON.
  • Hardcoding API keys in source files: Pasting secret keys into your script and pushing to GitHub exposes your account. Store keys in environment variables instead.
  • Assuming nested JSON keys always exist: Real API responses sometimes omit optional fields. Use .get() with sensible defaults instead of bare bracket lookups on optional keys.

Try It Yourself

  • Celsius & Fahrenheit Toggle (weather_units.py): Ask the user whether they prefer Celsius or Fahrenheit, and convert the temperature before displaying it.
  • Favorite Cities Dashboard (favorite_cities.py): Save a list of favorite cities in cities.json and loop through them to show a multi-city weather table in one run.
  • Public Fact Fetcher (random_fact.py): Send a GET request to a free public JSON API (such as https://catfact.ninja/fact), check the status code, and print the returned fact cleanly.

Frequently Asked Questions

What does HTTP status code 200 vs. 404 vs. 429 mean?

200 means the request succeeded, 404 means the URL or resource was not found, and 429 (Too Many Requests) means you hit the API’s rate limit and need to wait before calling again.

Why do I get ModuleNotFoundError: No module named ‘requests’?

requests is a third-party library, not part of the standard library. Activate your .venv virtual environment and install it with python -m pip install requests.

What is the difference between response.text and response.json()?

response.text gives you the raw response as one plain string, while response.json() parses that JSON string directly into Python dictionaries and lists.

How do I set an environment variable for an API key on Windows or macOS/Linux?

In PowerShell, run $env:MY_API_KEY="your_key_here" before running your script. On macOS or Linux, run export MY_API_KEY="your_key_here" in your terminal.

Want to organize growing API projects cleanly across multiple files? Check out the previous lesson: Creating Custom Modules and Multi-File Projects. In our next article, Introduction to Web Scraping with BeautifulSoup, you will learn how to extract structured data ethically from HTML web pages when no API is available.

Learning programming works best as a collaborative process, and your questions and insights help make these tutorials more effective for everyone. If you hit an HTTP error, have trouble reading nested JSON from an API, or build a fun upgrade to the weather dashboard, please share your experience in the comments. Your feedback helps create a learning community where we can all benefit from each other’s discoveries and solutions.

You Might Also Like

Comments

Loading comments…

Leave a Comment

0/5000