pip, Virtual Environments and Calling APIs
Python's huge strength is its packages. pip installs them, and a virtual environment keeps each project's packages separate, so projects don't break each other.
Different projects need different package versions - one old project may need version 1 of a library, a new one version 2. Installing everything globally causes clashes. A virtual environment is a private folder of packages for one project. Professional Python developers create one for every project, and list the needed packages in requirements.txt so teammates can install the same versions.
python -m venv .venv # make the environment (once per project)
# switch it on:
.venv\Scripts\activate # Windows
source .venv/bin/activate # macOS / Linux
pip install requests # install a package
pip freeze > requirements.txt # save the list of packages
pip install -r requirements.txt # install them all on another computer.venv to .gitignore. Share requirements.txt, not the environment folder.Calling an API with requests
import requests
res = requests.get("https://jsonplaceholder.typicode.com/users/1", timeout=10)
res.raise_for_status() # stop with an error for 404, 500...
user = res.json()
print(user["name"], "-", user["address"]["city"])
new = requests.post(
"https://jsonplaceholder.typicode.com/posts",
json={"title": "Review", "body": "Great product!"},
timeout=10,
)
print(new.status_code, new.json()["id"])An API lets your program get live data - weather, exchange rates, products, your own app's data - over the internet. The requests package makes calling APIs easy: send a request, check the status code, read the JSON. This is how Python scripts automate work with websites and online services.
jsonplaceholder.typicode.com is a free practice API. Run this on your computer after installing requests.
Handling problems
import requests
try:
res = requests.get("https://api.example.com/prices", timeout=5)
res.raise_for_status()
data = res.json()
except requests.Timeout:
print("The server is too slow, try again later")
except requests.HTTPError as e:
print("Server error:", e.response.status_code)
except requests.RequestException as e:
print("Network problem:", e)timeout. Without one, your program can wait forever if the server never answers. And keep API keys in environment variables (os.environ["API_KEY"]), never in your code.- python -m venv .venv creates an isolated environment per project.
- pip install and requirements.txt manage packages.
- requests.get / post call APIs; check status codes; set a timeout.
- Keep API keys in environment variables.
