An API (Application Programming Interface) lets your program talk to another service over the internet - weather data, currency conversion, or any web platform's data. This is how Python code stops being isolated and starts interacting with the real world.

Making your first API request

The requests library (install with pip install requests) is the standard way to call an API in Python:

import requests

response = requests.get("https://api.github.com/users/octocat")
data = response.json()

print(data["name"])
print(data["public_repos"])

Understanding the response

Most APIs return data as JSON - a text format that maps almost directly onto Python dictionaries and lists. response.json() parses that text into a Python dictionary you can index normally, as shown above.

Checking for errors

Real code should never assume a request succeeded - networks fail, APIs go down, and endpoints change:

response = requests.get("https://api.github.com/users/octocat")
if response.status_code == 200:
    data = response.json()
    print(data["name"])
else:
    print("Request failed with status:", response.status_code)

Sending data with a POST request

payload = {"name": "Riya", "email": "riya@example.com"}
response = requests.post("https://example.com/api/signup", json=payload)
print(response.status_code)

Where this leads

Once you are comfortable calling APIs, you can pull in real data for any project - weather for a dashboard, exchange rates for a currency converter, or, as covered in the AI Fundamentals course, calling an AI model's API to add intelligent features to your own programs.