Clouds, Kubernetes, monitoring and CI/CD all speak HTTP and JSON, so calling
APIs is a big part of DevOps automation. This module covers how to call them and
handle their data in Python with the requests
library.
- Call a public API with
requests.get()and parse JSON with.json() - Work with
list,dict, andset - Read and write files, including JSON
- Keep API keys out of source code using environment variables
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txtcollections_demo.py— list / dict / set basicscall_api.py— fetch and filter a JSONPlaceholder todojokes_api.py— switch between two endpoints at runtimefile_io.py— read/write text and JSON filesstock_market_api.py— a real API using a key from an env var
python collections_demo.py
python call_api.py
# stock_market_api needs a free Alpha Vantage key
export ALPHAVANTAGE_API_KEY="your_key_here"
python stock_market_api.pyNever hardcode API keys in source — stock_market_api.py reads the key from
ALPHAVANTAGE_API_KEY. Get a free key at
https://www.alphavantage.co/support/#api-key
Fetch a GitHub user and save it to JSON:
- Call
https://api.github.com/users/<username>. - Print
name,public_repos,followers,location. - Save the full response to
github_user.jsonwithjson.dump(..., indent=2). - Bonus: handle a non-existent user (GitHub returns 404) with
response.raise_for_status()inside atry / except.