JSON, YAML & calling APIs
DevOps is full of structured data: API responses are JSON, Kubernetes manifests and CI pipelines are YAML, and tools talk to each other over HTTP. This chapter goes beyond the quick JSON example from earlier: reading and writing both formats safely, and calling web APIs without your script hanging or crashing on the first network hiccup.
JSON in and out
JSON types map directly onto Python types:
| JSON | Python |
|---|---|
object {"a": 1} | dict |
array [1, 2] | list (tuples are written as arrays too) |
| string, number | str, int / float |
true / false / null | True / False / None |
The four functions: loads/dumps work with strings, load/dump work with open files.
import json
text = '{"service": "api", "replicas": 3, "debug": false}'
data = json.loads(text) # str -> dict
data["debug"] # False
data["replicas"] = 5
json.dumps(data) # '{"service": "api", "replicas": 5, "debug": false}'
print(json.dumps(data, indent=2, sort_keys=True))
# {
# "debug": false,
# "replicas": 5,
# "service": "api"
# }
json.dumps({"name": "café"}) # '{"name": "caf\u00e9"}'
json.dumps({"name": "café"}, ensure_ascii=False) # '{"name": "café"}'
indent makes output readable, sort_keys=True keeps key order stable (nice for diffs in git), and ensure_ascii=False keeps non-English letters readable instead of \u codes.
A config file with defaults
import json
DEFAULTS = {"port": 8080, "log_level": "INFO", "timeout": 5}
def load_config(path):
try:
with open(path, encoding="utf-8") as f:
user = json.load(f)
except FileNotFoundError:
user = {}
return {**DEFAULTS, **user} # values from the file win over the defaults
config = load_config("config.json")
with open("config.json", "w", encoding="utf-8") as f:
json.dump(config, f, indent=2)
From the shell, python3 -m json.tool config.json pretty-prints a file and reports exactly where it's broken, and curl -s URL | python3 -m json.tool does the same for an API response.
Errors you'll see:
Expecting property name enclosed in double quotes: line 1 column 2 (char 1): JSON needs double quotes, so{'a': 1}(Python style) is invalid. A trailing comma gives the same message in Python 3.12 (3.13 and newer sayIllegal trailing comma).Expecting value: line 1 column 1 (char 0): the text is empty or isn't JSON at all, typically an HTML error page from an API.TypeError: Object of type datetime is not JSON serializable: convert it first, or passdefault=strtodumps.
YAML with PyYAML
YAML is what humans write config in: CI pipelines, Docker Compose, Kubernetes, Ansible. Install with pip install PyYAML, import as yaml.
# services.yaml
timeout: 5
services:
- name: api
url: http://localhost:8000/health
- name: website
url: https://demee.cc
import yaml
with open("services.yaml", encoding="utf-8") as f:
config = yaml.safe_load(f) # -> {'timeout': 5, 'services': [{...}, {...}]}
for svc in config["services"]:
print(svc["name"], svc["url"])
print(yaml.safe_dump(config, sort_keys=False)) # dict -> YAML text
- Always use
safe_load. Fullyaml.loadcan build arbitrary Python objects from a file, which is dangerous with untrusted input; in PyYAML 6 it won't even run without an explicitLoader. - Files with several documents separated by
---(common in Kubernetes) needyaml.safe_load_all(f), which yields one dict per document. - YAML indentation must be spaces; a tab gives a
ScannerError. - YAML guesses types.
country: NOloads asFalse,yes/onasTrue, andversion: 3.10as the number3.1. Quote anything that must stay text:version: "3.10".
Calling APIs with requests
requests (pip install requests) is the standard HTTP library. A request has a method (GET to read, POST to create or send), a URL, optional headers and optionally a body; the response has a status code, headers and a body.
resp.status_code (or call raise_for_status()) before trusting the body, and always pass a timeout.import requests
resp = requests.get(
"https://api.github.com/search/repositories",
params={"q": "topic:devops", "sort": "stars", "per_page": 5}, # the ?query=string
headers={"Accept": "application/vnd.github+json"},
timeout=10,
)
print(resp.url) # https://api.github.com/search/repositories?q=topic%3Adevops&sort=stars&per_page=5
print(resp.status_code) # 200
resp.raise_for_status() # raises HTTPError for any 4xx / 5xx
for repo in resp.json()["items"]: # .json() parses the body into a dict
print(repo["full_name"], repo["stargazers_count"])
params=builds and URL-encodes the query string for you.- Always pass
timeout=. requests has no default timeout, so a server that never answers makes your script wait forever. raise_for_status()turns error status codes into exceptions. Without it, a 404 or 500 looks like a normal response.resp.textis the raw body,resp.headersthe response headers (case-insensitive dict).
Sending data: json= encodes a dict as JSON and sets Content-Type: application/json, which is what most APIs and chat webhooks expect. data= sends it as an HTML form instead. Secrets come from the environment, never from the code:
import os
import requests
resp = requests.post(
os.environ["WEBHOOK_URL"],
json={"text": "Deploy of api finished"}, # Slack uses "text"; Discord uses "content"
headers={"Authorization": f"Bearer {os.environ['API_TOKEN']}"},
timeout=10,
)
resp.raise_for_status()
Handling network errors
All requests errors inherit from requests.exceptions.RequestException, so you can catch specific ones first and everything else at the end:
import requests
def get_json(url):
try:
resp = requests.get(url, timeout=5)
resp.raise_for_status()
return resp.json()
except requests.exceptions.Timeout:
print(f"{url}: timed out")
except requests.exceptions.ConnectionError:
print(f"{url}: could not connect (DNS, refused, network down)")
except requests.exceptions.HTTPError as e:
print(f"{url}: HTTP {e.response.status_code}")
except requests.exceptions.JSONDecodeError:
print(f"{url}: answered, but not with JSON")
return None
The GitHub API is a good one to practise on: public data needs no token, but unauthenticated requests are limited to 60 per hour per IP address. Send a token in the Authorization header to get a higher limit, and read resp.headers["X-RateLimit-Remaining"] to see how many calls you have left.
A realistic script: check every health endpoint
This reads the services.yaml from above, checks each URL with a couple of retries for network blips, prints a summary and exits non-zero if anything is down, so cron or a CI job can react.
#!/usr/bin/env python3
"""check_services.py - hit every health endpoint listed in services.yaml."""
import sys
import time
import requests
import yaml
def check(url, timeout, retries=2):
"""Return (ok, detail). Retries only connection problems, not HTTP errors."""
for attempt in range(1, retries + 2):
try:
resp = requests.get(url, timeout=timeout)
resp.raise_for_status()
ms = resp.elapsed.total_seconds() * 1000
return True, f"{resp.status_code} in {ms:.0f} ms"
except requests.exceptions.HTTPError as e:
return False, f"HTTP {e.response.status_code}" # it answered: don't retry
except requests.exceptions.RequestException as e:
if attempt > retries:
return False, type(e).__name__
time.sleep(2 ** attempt) # wait 2 s, then 4 s
def main():
with open("services.yaml", encoding="utf-8") as f:
config = yaml.safe_load(f)
timeout = config.get("timeout", 5)
failed = 0
for svc in config["services"]:
ok, detail = check(svc["url"], timeout)
print(f"{'OK ' if ok else 'BAD'} {svc['name']:<10} {detail}")
if not ok:
failed += 1
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
$ python check_services.py
OK api 200 in 3 ms
BAD website HTTP 503
BAD admin ConnectionError
$ echo $?
1