Your DevOps study space

Real explanations. Videos with tests. Fresh exams every time. Keep the streak alive and watch the XP stack up.

JSON, YAML & calling APIs · Python Docs · StackwisePlanDevOps JSON, YAML & calling APIs · Python Docs · StackwiseCodePython JSON, YAML & calling APIs · Python Docs · StackwiseBuildDocker JSON, YAML & calling APIs · Python Docs · StackwiseTestDevOps JSON, YAML & calling APIs · Python Docs · StackwiseReleaseGit JSON, YAML & calling APIs · Python Docs · StackwiseDeployKubernetes JSON, YAML & calling APIs · Python Docs · StackwiseOperateLinux JSON, YAML & calling APIs · Python Docs · StackwiseMonitorDevOps

Pick a topic

Eight tracks, each with docs, a cheat sheet, videos and tests.

How it works

One loop, repeated until it sticks.

Jump back in

Picked up from where you left off.

Free forever

Your DevOps journey starts with one click.

Sign in with Google or GitHub to open every chapter, video, test and challenge. Your progress is saved wherever you learn.

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:

JSONPython
object {"a": 1}dict
array [1, 2]list (tuples are written as arrays too)
string, numberstr, int / float
true / false / nullTrue / 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 say Illegal 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 pass default=str to dumps.

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. Full yaml.load can build arbitrary Python objects from a file, which is dangerous with untrusted input; in PyYAML 6 it won't even run without an explicit Loader.
  • Files with several documents separated by --- (common in Kubernetes) need yaml.safe_load_all(f), which yields one dict per document.
  • YAML indentation must be spaces; a tab gives a ScannerError.
  • YAML guesses types. country: NO loads as False, yes/on as True, and version: 3.10 as the number 3.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.

your scriptrequests.get(url)the APIapi.github.comGET + params + headers200 OK + JSON bodyresp.json()text -> Python{"items": [{"name": ...}, ...]}a dict you can loop over
Check 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.text is the raw body, resp.headers the 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

Questions

Pick an answer. Get it wrong and you can try again right away, no waiting. 10 questions per topic - pick a filter below, then use Recreate questions for a fresh set on that topic.

Fresh questions every time

Exam

A mixed test across the whole site, shuffled so you never know which topic comes next. When you submit, every mistake comes with the reason and a jump to the exact moment in the video that explains it.

30 questions 6 topics 20 minute limit Up to 70 XP
1–4 answer · ←→ move
History

Essay

0 / 200-250 words
Sample answer
History
0:00 / 0:00
Not started

on YouTube
Subscribe

Topic progress

Activity

Achievements

Settings

Your profile and your account.

Profile details

* Required. Saved in this browser until you sign in.

Letters, numbers, dots, dashes and underscores.
0 / 160

Account

Checking…

App

Install Stackwise on your phone or computer. It opens in its own window from your home screen, and the Docs and cheat sheets you've opened keep working without internet.

Only admins can see this

Dashboard

Sign-ups, activity, messages and reviews in one place.

Prove it

Certificates

Pass a topic's test and get a certificate with its own public page you can share or add to LinkedIn. Each test is 10 questions drawn at random and graded on the server; you need 8 right, you have 15 minutes, and you get one try per topic a day.

From first command to production

Linux for DevOps

A path through Linux the way DevOps engineers use it: ten stages, every command explained with its flags, examples, real output and mistakes, the combinations engineers chain together, and incidents worked through step by step. Practise everything in a safe lab folder.

Before the interview

Interview prep

Questions that come up in real DevOps interviews, with the kind of answer that lands. Say yours out loud first, then compare. Each one links to the chapter that goes deeper.

    Private to you

    My notes

    Everything you wrote down while watching and reading, in one place. Saved to your account, never shown to anyone.