Working with APIs and Virtual Environments
Virtual environments
python -m venv venv
source venv/bin/activate # on Windows: venvScriptsactivate
pip install requests
A virtual environment keeps one project’s installed packages isolated from every other project on your machine. Without one, installing a specific version of a package for one project can silently break a completely different project that depends on a different version of the same package. Always create one per project rather than installing packages globally — this is standard practice on every professional Python team.
Calling a real API
import requests
response = requests.get("https://api.github.com/users/octocat")
data = response.json()
print(data["name"], data["public_repos"])
requests is the most widely used third-party library in the Python ecosystem for making HTTP calls. response.json() automatically parses a JSON response body into a Python dictionary, so you can access fields the same way you would with any dictionary you built yourself.
Checking the status code
response = requests.get("https://api.github.com/users/octocat")
print(response.status_code) # 200 means success
if response.status_code == 200:
data = response.json()
else:
print(f"Request failed with status {response.status_code}")
Never assume an API call succeeded just because your code didn’t crash — a 404 or 500 response still returns normally as far as Python is concerned, so checking status_code explicitly is essential before trusting the response body.
Handling errors gracefully
try:
response = requests.get("https://api.example.com/data", timeout=5)
response.raise_for_status()
data = response.json()
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
A timeout stops your program from hanging indefinitely if a server never responds, and raise_for_status() automatically raises an exception for any error status code, so you can catch every kind of failure — timeouts, connection errors, and bad status codes — in one place.
You’ve completed the course
From your first print() statement to calling real APIs with proper error handling and isolated environments — you now have a professional-level Python foundation. Take the certification assessment next, or apply to an internship to put it to work on a real project.