Velamuvi AIAcademy

Lesson 12 of 12 · Calling APIs From Python

Project: Call a Public API

Put everything together: read API documentation, chain two free APIs from Open-Meteo, handle errors and timeouts, and build a weather report for any city in Python.

  • 9 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • How to read API documentation and plan a program around it
  • How to chain two APIs, where one answer feeds the next request
  • How to turn a nested JSON response into a clear report
  • How to make an API program robust with timeouts and error handling

What you will build

A weather report for any city in the world. You type a city name, and the program prints the current temperature and wind, plus a three-day forecast:

Hyderabad, India
Now: 28.5 °C, wind 12.0 km/h
2026-11-17   max 29.9 °C   min 20.2 °C
2026-11-18   max 29.5 °C   min 21.3 °C
2026-11-19   max 28.3 °C   min 19.3 °C

You will use two free APIs from Open-Meteo, which need no key:

  1. A geocoding API, which turns a city name into coordinates.
  2. A forecast API, which turns coordinates into weather.

Step 0: read the documentation

Before writing code, read what the API offers. Open-Meteo's documentation is at open-meteo.com, under "Docs".

From the documentation, this is what we need:

EndpointParameters we useWhat it returns
https://geocoding-api.open-meteo.com/v1/searchname, counta list of matching places with latitude, longitude and country
https://api.open-meteo.com/v1/forecastlatitude, longitude, current, daily, timezone, forecast_daysthe weather, under current and daily

Make a plan in plain words: find the city, get its weather, print a report, and handle anything that goes wrong.

Step 1: find the city

Try it yourselfPython
import requests

response = requests.get(
    "https://geocoding-api.open-meteo.com/v1/search",
    params={"name": "Hyderabad", "count": 1},
    timeout=10,
)
response.raise_for_status()
place = response.json()["results"][0]

print(place["name"], place["country"])
print("Latitude:", place["latitude"], "Longitude:", place["longitude"])

Step 2: get the weather, and look at its shape

Feed the coordinates from step 1 into the forecast API. The first time you use an endpoint, print the whole response neatly so you can see its shape:

Try it yourselfPython
import json
import requests

response = requests.get(
    "https://api.open-meteo.com/v1/forecast",
    params={
        "latitude": 17.38,
        "longitude": 78.46,
        "current": "temperature_2m,wind_speed_10m",
        "daily": "temperature_2m_max,temperature_2m_min",
        "timezone": "auto",
        "forecast_days": 3,
    },
    timeout=10,
)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))

Two things stand out. The current weather is a simple object. The daily forecast is three parallel lists: the first date goes with the first maximum and the first minimum, and so on.

Step 3: turn the data into a report

Here is a real response saved as text, so you can work on the report without the internet:

Try it yourselfPython
import json

body = """{"latitude": 17.398945, "longitude": 78.457085, "timezone": "Asia/Kolkata",
"current_units": {"temperature_2m": "°C", "wind_speed_10m": "km/h"},
"current": {"time": "2026-11-17T16:30", "temperature_2m": 28.5, "wind_speed_10m": 12.0},
"daily": {"time": ["2026-11-17", "2026-11-18", "2026-11-19"],
          "temperature_2m_max": [29.9, 29.5, 28.3],
          "temperature_2m_min": [20.2, 21.3, 19.3]}}"""

data = json.loads(body)
now = data["current"]
units = data["current_units"]
print(f"Now: {now['temperature_2m']} {units['temperature_2m']}, wind {now['wind_speed_10m']} {units['wind_speed_10m']}")

days = data["daily"]
for i in range(len(days["time"])):
    print(f"{days['time'][i]}   max {days['temperature_2m_max'][i]} °C   min {days['temperature_2m_min'][i]} °C")

Because the lists are parallel, one index i picks the matching date, maximum and minimum.

Step 4: make it robust

A real program must survive a misspelt city, a slow server and a lost connection. Two careful functions keep each API call in one place:

def find_city(name):
    """Return (name, country, latitude, longitude), or None if no city matches."""
    response = requests.get(GEOCODING_URL, params={"name": name, "count": 1}, timeout=10)
    response.raise_for_status()
    results = response.json().get("results")
    if not results:
        return None
    place = results[0]
    return place["name"], place.get("country", ""), place["latitude"], place["longitude"]

Notice .get("results"). When nothing matches, Open-Meteo leaves the results field out completely, so ["results"] would crash with a KeyError.

Step 5: the complete program

Here is everything together. It reports on several cities, including one that does not exist, so you can see the error handling at work. Run it, then change the list of cities.

Try it yourselfPython
import time
import requests

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


def find_city(name):
    """Return (name, country, latitude, longitude), or None if no city matches."""
    response = requests.get(GEOCODING_URL, params={"name": name, "count": 1}, timeout=10)
    response.raise_for_status()
    results = response.json().get("results")
    if not results:
        return None
    place = results[0]
    return place["name"], place.get("country", ""), place["latitude"], place["longitude"]


def get_weather(latitude, longitude):
    """Return the forecast data for a location."""
    params = {
        "latitude": latitude,
        "longitude": longitude,
        "current": "temperature_2m,wind_speed_10m",
        "daily": "temperature_2m_max,temperature_2m_min",
        "timezone": "auto",
        "forecast_days": 3,
    }
    response = requests.get(FORECAST_URL, params=params, timeout=10)
    response.raise_for_status()
    return response.json()


def print_report(city_name):
    try:
        place = find_city(city_name)
        if place is None:
            print(f"Sorry, no city called '{city_name}' was found.")
            return
        name, country, latitude, longitude = place
        data = get_weather(latitude, longitude)
    except requests.exceptions.HTTPError as error:
        print(f"The weather service answered with an error: {error.response.status_code}")
        return
    except requests.exceptions.RequestException:
        print("Could not reach the weather service. Check your connection and try again.")
        return

    now = data["current"]
    print(f"{name}, {country}")
    print(f"Now: {now['temperature_2m']} °C, wind {now['wind_speed_10m']} km/h")
    days = data["daily"]
    for i in range(len(days["time"])):
        print(f"{days['time'][i]}   max {days['temperature_2m_max'][i]} °C   min {days['temperature_2m_min'][i]} °C")


for city in ["Hyderabad", "London", "Notarealcityname"]:
    print_report(city)
    print()
    time.sleep(0.5)        # be polite: a short pause between cities

Look at how the lessons of this course appear in it:

  • Requests and responses, GET, query parameters with params= and JSON parsing with .json().
  • Status codes checked with raise_for_status().
  • Timeouts on every request, and errors handled in one place with clear messages.
  • Throttling with a short pause between cities.
  • No API key is needed here, but the Session and header patterns you learned would slot straight in.

Ideas to extend it

  • Ask the user for a city with input() when you run it on your own computer.
  • Add "temperature_unit": "fahrenheit" to the parameters as an option.
  • Add more daily fields, such as precipitation_sum or sunrise, from the documentation.
  • Save each report to a CSV file to build a weather history.
  • Add the retry loop from the last lesson for 429 and 5xx errors.
Practice exercise

Turn a saved forecast response into a daily summary, and find the hottest day.

Your solutionPython
import json

# A saved forecast response (daily part only)
body = """{"daily": {"time": ["2026-11-17", "2026-11-18", "2026-11-19", "2026-11-20"],
"temperature_2m_max": [29.9, 31.2, 28.3, 30.4],
"temperature_2m_min": [20.2, 21.3, 19.3, 20.8]}}"""

# 1. Parse the JSON and print one line per day: <date>: <min> to <max> °C
# 2. Then print the hottest day (the highest max) as: Hottest: <date> (<max> °C)

# Output must be exactly:
# 2026-11-17: 20.2 to 29.9 °C
# 2026-11-18: 21.3 to 31.2 °C
# 2026-11-19: 19.3 to 28.3 °C
# 2026-11-20: 20.8 to 30.4 °C
# Hottest: 2026-11-18 (31.2 °C)
Knowledge check

In the project, why does find_city() use .get('results') instead of ['results']?

Summary

  • Start every API project by reading the documentation and planning in plain words.
  • Chain APIs: the answer from one request (the coordinates) becomes the parameters of the next.
  • Print an unfamiliar response with json.dumps(..., indent=2) before writing code for it.
  • Make programs robust: timeouts, raise_for_status(), .get() for optional fields and friendly messages.

You have finished APIs and HTTP Fundamentals

You now understand how programs talk over the web: requests and responses, methods, status codes, JSON, headers, query parameters and bodies, API keys, the requests library, errors, timeouts, rate limits and retries. These are exactly the skills you need to use AI model APIs.

Where next?

Finished reading? Tick it off to track your progress.