Working With APIs and HTTP Requests
Prerequisites: Modules, Packages
The requests package (pip install requests) is the standard way to
call a web API from Python.
import requests
response = requests.get("https://api.github.com/users/octocat")
print(response.status_code)
data = response.json()
print(data["login"])
Expected output
200
octocat
.status_code tells you whether the request succeeded (200) or
failed (404 not found, 500 server error, etc.); .json() parses a
JSON response body straight into a Python dictionary.
Common mistakes
- Not checking
status_code(or catchingrequests.RequestException) before assuming.json()will contain useful data — a failed request can return an error page instead of the expected JSON.