Lesson 06 · 45 minutes
Call a web API safely with the standard library
- Run a small JSON API on your own machine and call it from Python
- Set a timeout and handle status codes and network errors
- Pass a secret to a program through an environment variable
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
A threat-intelligence feed publishes bad addresses with a score, and your team wants them in your tools. The feed needs an API key. Your first draft of a client had the key in the source file, no timeout, and it treated every answer as good data. Your task is to write the client again, so that it reads the key from the environment, never waits for ever and reports a status code that is not 200. You test it against a feed that runs on your own machine.
Recall
Lesson 5: what exit code does argparse give when a required argument is missing?
2. argparse prints the usage line and the error to standard error, and exits with the code 2 for bad usage, as many Unix tools do.
Lesson 4: json.load reads a file. What Python types do you get back?
Dictionaries, lists, strings, numbers, booleans and None (JSON null). The response of an API is the same shape, so you use it with ["key"] and .get as in lesson 2.
The idea
HTTP is a request and a response. The request has a method (GET reads), a path, and headers. The response has a status code, headers and a body.
| Status | Meaning |
|---|---|
200 | It worked. |
401 | You did not prove who you are (bad or missing key). |
404 | The path does not exist. |
5xx | The server failed. |
The standard library is enough: urllib.request makes the call, json reads the body, and http.server can be the server. Nothing is installed.
A secret (an API key) must not live in the code. The program reads it from an environment variable, a named value that the shell passes to the programs that it starts.
- Your script → urllib: Request with a key header
- urllib → API server: GET /blocklist
- API server → urllib: status, headers, JSON body
- urllib → Your script: a dictionary, or an error
Worked example
1. Write the API
Create api.py in ~/krlab/python. It is a lab server: save it and run it, but do not study it. Writing a server is not the skill of this lesson, and it uses classes, which you do not need yet. It is a small JSON service with three useful paths: /health, /slow (it answers after three seconds) and /blocklist (it needs the key). It listens on 127.0.0.1 only, so nobody else on the network can reach it, and it refuses to start without a key. os.environ.get("KR_API_KEY") reads an environment variable, and gives None when it is not set. The client in step 4 is the part to learn.
api.py
import json
import os
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
KEY = os.environ.get("KR_API_KEY")
BLOCKLIST = ["203.0.113.7", "198.51.100.23"]
class Handler(BaseHTTPRequestHandler):
def reply(self, status, payload):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/health":
self.reply(200, {"status": "ok"})
elif self.path == "/slow":
time.sleep(3)
self.reply(200, {"status": "late"})
elif self.path == "/blocklist":
if self.headers.get("X-Api-Key") != KEY:
self.reply(401, {"error": "bad or missing key"})
else:
self.reply(200, {"addresses": BLOCKLIST})
else:
self.reply(404, {"error": "not found"})
if not KEY:
sys.exit("set KR_API_KEY first")
ThreadingHTTPServer(("127.0.0.1", 8100), Handler).serve_forever()2. Start it with a random key
secrets makes unpredictable values. export puts the key in the environment of this shell, so every program that the shell starts can read it. $(...) puts the output of a command into the line. The & at the end starts the server in the background, and 2> api.log keeps its request log in a file.
cd ~/krlab/python
export KR_API_KEY=$(python3 -c "import secrets; print(secrets.token_hex(8))")
python3 api.py 2> api.log &[1] 41873The number is the process ID, and yours differs. The server keeps running in the background. If the port 8100 is busy on your machine, change the number in api.py and in client.py.
3. Look at the raw exchange
curl calls a URL from the terminal. -i includes the response headers. This is the address that it calls:
curl -i http://127.0.0.1:8100/healthHTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.14.4
Date: Sat, 21 Nov 2026 08:37:22 GMT
Content-Type: application/json
Content-Length: 16
{"status": "ok"}The first line holds the status, then come the headers, an empty line and the body.
4. Write the client
Create client.py. The new parts:
urllib.request.Request(url, headers=...)builds a request, andadd_headeradds one more header.urllib.request.urlopen(request, timeout=2)sends it.timeoutis in seconds and applies to each wait on the network. Thewithblock closes the connection.response.statusis the status code, andjson.load(response)reads the body.urlopenraisesHTTPErrorfor a 4xx or 5xx code, andURLErrorwhen it cannot connect.HTTPErroris a kind ofURLError, so itsexceptcomes first.- The key comes from
os.environ, never from the file.
client.py
import json
import os
import urllib.error
import urllib.request
BASE = "http://127.0.0.1:8100"
def get_json(path, key=None, timeout=2):
request = urllib.request.Request(BASE + path, headers={"Accept": "application/json"})
if key:
request.add_header("X-Api-Key", key)
with urllib.request.urlopen(request, timeout=timeout) as response:
print(response.status, response.headers["Content-Type"])
return json.load(response)
def show(path, key=None, timeout=2):
try:
print(get_json(path, key=key, timeout=timeout))
except urllib.error.HTTPError as error:
print("HTTP error", error.code, error.reason)
except TimeoutError:
print("timeout")
except urllib.error.URLError as error:
print("cannot connect:", error.reason)
show("/health")
show("/missing")
show("/blocklist")
show("/blocklist", key=os.environ.get("KR_API_KEY"))
show("/slow", timeout=1)5. Run it
python3 client.py200 application/json
{'status': 'ok'}
HTTP error 404 Not Found
HTTP error 401 Unauthorized
200 application/json
{'addresses': ['203.0.113.7', '198.51.100.23']}
timeoutThe first call works. The second path does not exist. The third has no key, so the server answers 401. The fourth sends the key and gets the list. The fifth waits one second for a server that needs three, and the client gives up instead of hanging.
If client.py shows an error that this lesson does not show, run cat api.log. The words Address already in use mean that something else uses port 8100: change the number in both files.
6. Read the server log, then stop the server
The server wrote one line for each request, and the curl call counts too. Run cat api.log at once. One line has these parts:
jobs lists the background jobs of this terminal. kill %1 stops job 1: use the number that jobs shows for the server, and no other.
cat api.log
jobs
kill %1
python3 client.py127.0.0.1 - - [21/Nov/2026 08:37:22] "GET /health HTTP/1.1" 200 -
127.0.0.1 - - [21/Nov/2026 08:37:22] "GET /health HTTP/1.1" 200 -
127.0.0.1 - - [21/Nov/2026 08:37:22] "GET /missing HTTP/1.1" 404 -
127.0.0.1 - - [21/Nov/2026 08:37:22] "GET /blocklist HTTP/1.1" 401 -
127.0.0.1 - - [21/Nov/2026 08:37:22] "GET /blocklist HTTP/1.1" 200 -
[1]+ Running python3 api.py 2> api.log &
cannot connect: [Errno 111] Connection refused
cannot connect: [Errno 111] Connection refused
cannot connect: [Errno 111] Connection refused
cannot connect: [Errno 111] Connection refused
cannot connect: [Errno 111] Connection refusedWith the server gone, every call is refused. A client must expect this.
If you run cat api.log again after three seconds, it also shows the /slow request and a BrokenPipeError trace: the server wakes up from its sleep, and the client has already left. This is normal.
The key is still in the environment of this shell. unset KR_API_KEY removes it.
unset KR_API_KEYYour turn
Do the task of the feed. There is no code here: use what the worked example showed.
Save feed.py in ~/krlab/python. It is a small threat feed with an API key. It makes 25 invented addresses with scores, and the seed is fixed, so every reader gets the same list. It listens on 127.0.0.1 port 8150. /iocs returns all items, and /iocs/<address> returns one.
feed.py
import json
import os
import random
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
KEY = os.environ.get("KR_FEED_KEY")
rng = random.Random(6)
SCORES = {}
while len(SCORES) < 25:
SCORES[f"203.0.113.{rng.randint(1, 254)}"] = rng.randint(10, 99)
class Handler(BaseHTTPRequestHandler):
def reply(self, status, payload):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.headers.get("X-Api-Key") != KEY:
self.reply(401, {"error": "bad or missing key"})
elif self.path == "/iocs":
items = [{"address": a, "score": s} for a, s in SCORES.items()]
self.reply(200, {"count": len(items), "items": items})
elif self.path.startswith("/iocs/") and self.path[6:] in SCORES:
self.reply(200, {"address": self.path[6:], "score": SCORES[self.path[6:]]})
else:
self.reply(404, {"error": "not found"})
if not KEY:
sys.exit("set KR_FEED_KEY first")
ThreadingHTTPServer(("127.0.0.1", 8150), Handler).serve_forever()Start it with a new random key in KR_FEED_KEY, in the background, as in step 2. Then write feedclient.py. It must:
- Read the key from
KR_FEED_KEY, and send it in the headerX-Api-Key. The key must not be in the file. - Use a timeout of 2 seconds on every call.
- Call
/iocsand find the address with the highest score, and count the items with a score of 80 or more. - Ask for the address
198.51.100.200, which is not in the feed, and print the status code instead of crashing. - Call
/iocsonce more with a wrong key, and print the status code.
When you finish, run jobs and stop the server with kill %N (N is its job number). Run unset KR_FEED_KEY too. Then answer from your own results.
Check yourself
Why does every network call in your code need a timeout?
Without one, a server that accepts the connection and then says nothing blocks your program for ever. One slow feed can stop a whole monitoring job. A timeout turns the stall into an error that you can handle.
You store the key in a variable at the top of client.py and commit the file. What is the risk?
Anyone who can read the repository can use the key, and Git keeps the old versions, so deleting the line later does not remove it. You must treat the key as leaked and replace it. Read keys from the environment or from a secret store.
Why is "except urllib.error.URLError" placed after "except urllib.error.HTTPError"?
HTTPError is a subclass of URLError. Python uses the first except that matches, so the general one first would catch every HTTPError and hide the status code.
The server returns 200 with an HTML page that says "maintenance". What goes wrong when you call json.load?
It raises json.JSONDecodeError. A status code and a good body are two separate checks. Test the Content-Type header, and catch the decode error, before you trust the data.
Field notes
- The command line is visible to other users (
ps). An exported variable is visible in/proc/<pid>/environto the same user and to root. An environment variable is better than a source file, but a secret store or a file with mode0600is stronger. Never print a key into a log or a traceback. - Compare secrets with
hmac.compare_digest(a, b), not!=. A plain comparison can leak, through its timing, how many first characters are right. The lab server uses!=for brevity. - Never turn off TLS verification (
ssl._create_unverified_context, orverify=Falsein other libraries). That removes the only proof that you talk to the real server.urlopenchecks certificates forhttps://by default. urlopenfollows redirects, and it also opensfile://andftp://addresses. If the address comes from a user, check that the scheme ishttpsand that the host is on an allow-list. Otherwise the tool can be tricked into fetching internal services (server-side request forgery, SSRF: in the OWASP Top 10 2025 it is part of the category Broken Access Control).- Limit what you read.
response.read(1_000_000)stops at one megabyte, so a hostile server cannot fill your memory. For retries with back-off, use a library such asrequestsinside a venv (lesson 7), with the same timeout rule.