How Python communicates with web services and retrieves online data
An API (Application Programming Interface) allows different software systems to communicate. Web APIs let your Python programs interact with online services such as weather data, maps, social media, or databases.
HTTP (Hypertext Transfer Protocol) is the foundation of communication on the web. When your program interacts with an API, it sends HTTP requests and receives responses.
The requests library makes HTTP communication simple and readable.
pip install requests
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
print(response.json())
Most APIs return data in JSON format. You can convert it to Python objects using .json():
data = response.json()
print(data["current_user_url"])
Many APIs accept parameters to filter or customize results:
params = {"q": "python", "sort": "stars"}
response = requests.get("https://api.github.com/search/repositories", params=params)
print(response.json())
Always check for errors when calling APIs:
if response.status_code == 200:
print("Success!")
else:
print("Error:", response.status_code)
Some APIs require authentication using an API key. Never hard‑code keys in public code.
headers = {"Authorization": "Bearer YOUR_API_KEY"}
response = requests.get("https://api.example.com/data", headers=headers)
Now that you understand APIs and HTTP requests, you're ready to explore how to work with JSON data in Lesson 17: Working with JSON Data.
← Back to Lesson Index