Working with APIs (Requests & JSON)
Connect your Python code to the internet. Learn how to securely fetch data from REST APIs and parse the JSON responses.
The World of APIs
An API (Application Programming Interface) allows your Python script to communicate with external servers. Whether you want to fetch live weather data, crypto prices, or send an automated tweet, you'll be using APIs.
The Requests Library
While Python has built-in networking tools, the entire industry relies on a third-party library called requests because of its incredibly human-friendly syntax. (Install it via pip install requests).
import requests
# Sending a GET request to a public API
response = requests.get("https://api.github.com/users/octocat")
# Checking if the request was successful (HTTP 200)
if response.status_code == 200:
print("Successfully connected!")Parsing JSON Data
Almost all modern REST APIs return data formatted as JSON (JavaScript Object Notation). It looks exactly like nested Python dictionaries and lists. The requests library can parse this instantly.
data = response.json()
# Extracting specific data from the parsed JSON dictionary
username = data['login']
followers = data['followers']
print(f"{username} has {followers} followers.")