Module 2 · APIs, Reports and the Detector Project · Lesson 5 of 9

Query an API without falling over

Read JSON from a local mock API with a timeout, and handle connection errors, bad status codes and invalid JSON separately.

In this lesson · about 22 minutes

  • Always set a timeout on network calls
  • Handle each failure type on its own
  • Keep tokens out of source code

Security tools constantly call APIs: threat-intel lookups, SIEM queries, ticketing systems. Each call can fail in different ways, and each needs a different response:

FailureIn urllibWhat to do
Server says no (401, 404, 429, 500…)urllib.error.HTTPError (has .code)401: fix credentials, don't retry. 429/503: retry later, a bounded number of times
Can't connect at allurllib.error.URLErrorCheck the address, DNS, network
No answer in timeTimeoutErrorMaybe retry once; investigate if it repeats
Answer isn't valid JSONjson.JSONDecodeError (a ValueError)Log a safe snippet; don't crash the whole run

Order matters: HTTPError is a kind of URLError, so catch it first.

In a real script you'd write from urllib.request import urlopen. Here, a stand-in urlopen talks to a pretend local API at http://127.0.0.1:8000 so you can trigger every failure safely. And never hard-code real tokens: read them from an environment variable or a secrets manager.

Exercise

Practice challenge 04: a careful API client

Write fetch_json(path). Call urlopen("http://127.0.0.1:8000" + path, timeout=5) and return:

  • ("ok", data) with the parsed JSON on success
  • ("http_error", code) for an HTTPError
  • ("timeout", None) for a TimeoutError
  • ("connection_error", None) for any other URLError
  • ("bad_json", None) when the body isn't valid JSON

The mock API has /alerts (works), /private (401), /slow (times out), /down (refuses connections) and /broken (returns HTML).

Code that runs before yours
import json
from urllib.error import HTTPError, URLError

class _MockResponse:
    def __init__(self, status, body):
        self.status = status
        self._body = body
    def read(self):
        return self._body.encode("utf-8")
    def __enter__(self):
        return self
    def __exit__(self, *exc):
        return False

def urlopen(url, timeout=None):
    """Stands in for urllib.request.urlopen talking to a local mock API."""
    if timeout is None:
        raise RuntimeError("Always pass a timeout")
    path = url.split("127.0.0.1:8000", 1)[-1]
    if path == "/alerts":
        return _MockResponse(200, json.dumps({"alerts": [{"user": "root", "source_ip": "203.0.113.45", "count": 5}]}))
    if path == "/broken":
        return _MockResponse(200, "<html>Down for maintenance</html>")
    if path == "/private":
        raise HTTPError(url, 401, "Unauthorized", {}, None)
    if path == "/slow":
        raise TimeoutError("timed out")
    raise URLError("Connection refused")

Check your understanding0 of 3 correct

Question 1

1.Why catch HTTPError before URLError?

Question 2

2.An API keeps returning 401. Should your script retry in a loop?

Question 3

3.Where should an API token live?

Quiz score: 0 of 3

Exercises solved: 0 of 1

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. All data in this course is synthetic and uses documentation IP ranges. Never paste real authentication logs or credentials into online tools. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.