Lesson 2 of 6
Access and the First Call: Tokens, Secrets and Reading a Response
Start a practice copy of the customer's API, keep the access token out of your code, make one request and read the answer for what it reveals about the data.
7 minForward Deployed Engineering
After this lesson you will be able to handle an access token safely, make a first request to a customer's API, and read the answer for what it tells you about the data and the system.
Start the practice server
Fernhill has no test copy of its system, so this course gives you one. In your integration folder, create fake_api.py with this content. You do not need to study it. It stands in for Fernhill's system: it holds ten repairs, hands them out four at a time, and wants a token with every request.
"""A practice copy of Fernhill Housing's repairs API. It runs on your own machine.
Usage: python fake_api.py (leave it running; stop it with Ctrl+C)
"""
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse
TOKEN = "practice-token"
PAGE_SIZE = 4
FIELDS = ("ref", "addr", "postcode", "category", "priority", "reported", "status", "updated", "tenant_name", "tenant_phone")
ROWS = [
("R-2201", "14 Mill Lane", "FH1 2AB", "PLUMB", "P1", "02/03/2026 08:14", "Open", "2026-03-02T08:14:00", "J. Abbot", "01632 960101"),
("R-2202", "3 Orchard Court", "fh1 4cd", "ELEC", "P2", "02/03/2026 09:40", "open ", "2026-03-02T09:40:00", "M. Bell", "01632 960102"),
("R-2203", "27 Station Road", "FH2 7EF", "PLUMB", "P3", "02/03/2026 11:05", "Closed", "2026-03-03T16:20:00", "S. Carr", "01632 960103"),
("R-2204", "8 Quarry View", "", "HEAT", "P1", "03/03/2026 07:55", "Open", "2026-03-03T07:55:00", "D. Dunn", "01632 960104"),
("R-2205", "51 Mill Lane", "FH1 2AD", "ROOF", "P2", "03/03/2026 10:30", "OPEN", "2026-03-03T10:30:00", "P. Eves", "01632 960105"),
("R-2206", "2 Chapel Street", "FH3 1GH", "ELEC", "P1", "03/03/2026 13:15", "Cancelled", "2026-03-04T09:00:00", "R. Finn", "01632 960106"),
("R-2207", "19 Orchard Court", "FH1 4CE", "PEST", "P3", "04/03/2026 08:20", "Open", "2026-03-04T08:20:00", "L. Gray", "01632 960107"),
("R-2208", "6 Station Road", "FH2 7EG", "HEAT", "P2", "04/03/2026 09:45", "Open", "2026-03-04T09:45:00", "T. Hale", "01632 960108"),
("R-2209", "33 Quarry View", "FH4 5JK", "PLUMB", "P1", "4/3/2026 12:10", "Open", "2026-03-04T12:10:00", "N. Ives", "01632 960109"),
("R-2210", "11 Chapel Street", "FH3 1GJ", "ROOF", "P3", "05/03/2026 08:05", "Closed", "2026-03-05T15:30:00", "K. Jay", "01632 960110"),
]
REPAIRS = [dict(zip(FIELDS, row)) for row in ROWS]
class Handler(BaseHTTPRequestHandler):
limited = False # page 2 is refused once and then served, so that you can practise retrying
def reply(self, status, body, headers=()):
data = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
for name, value in headers:
self.send_header(name, value)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
url = urlparse(self.path)
query = parse_qs(url.query)
if self.headers.get("Authorization") != f"Bearer {TOKEN}":
return self.reply(401, {"error": "missing or wrong token"})
if url.path != "/repairs":
return self.reply(404, {"error": "not found"})
page = int(query.get("page", ["1"])[0])
if page == 2 and not Handler.limited:
Handler.limited = True
return self.reply(429, {"error": "too many requests"}, [("Retry-After", "1")])
Handler.limited = False
since = query.get("updated_since", [""])[0]
items = [repair for repair in REPAIRS if repair["updated"] > since]
pages = max(1, -(-len(items) // PAGE_SIZE))
start = (page - 1) * PAGE_SIZE
self.reply(200, {"items": items[start : start + PAGE_SIZE], "page": page, "pages": pages})
if __name__ == "__main__":
print("Practice API running on http://127.0.0.1:8765 (Ctrl+C to stop)")
HTTPServer(("127.0.0.1", 8765), Handler).serve_forever()Open a terminal in the folder and start it:
python fake_api.pyIt prints one line saying that it is running and then waits. Leave that terminal alone and open a second one in the same folder for everything else. The server only answers programs on your own machine.
Keep the token out of the code
The token for the practice server is practice-token. It protects nothing, which is the only reason it can appear in a lesson. A real token lets anyone who holds it read the customer's data, so treat it as you would a password.
That means the token is never written in a file of code, because code is copied, shared and kept in version history for years. A program reads it from an environment variable when it starts. On a server, a secrets store fills that variable in. On your own machine you set it by hand, in the second terminal:
macOS or Linux:
export REPAIRS_TOKEN=practice-token
Windows PowerShell:
$env:REPAIRS_TOKEN = "practice-token"The variable lasts until you close that terminal. If a real token ever ends up in a message, a ticket or a commit, do not just delete it. Tell the system's owner and ask for it to be replaced, because you cannot know who has already read it.
Make the first call
Create first_call.py. It makes one request, for the first page of repairs, and prints the status, the paging details and one repair in full.
"""Make one request to the repairs API and show what comes back."""
import json
import os
import urllib.request
BASE = os.environ.get("REPAIRS_API", "http://127.0.0.1:8765")
TOKEN = os.environ["REPAIRS_TOKEN"]
request = urllib.request.Request(f"{BASE}/repairs?page=1", headers={"Authorization": f"Bearer {TOKEN}"})
with urllib.request.urlopen(request, timeout=10) as response:
status = response.status
body = json.load(response)
print("status:", status)
print("page", body["page"], "of", body["pages"], "with", len(body["items"]), "items")
print(json.dumps(body["items"][1], indent=2))Run it in the second terminal:
python first_call.pyIt prints this:
status: 200
page 1 of 3 with 4 items
{
"ref": "R-2202",
"addr": "3 Orchard Court",
"postcode": "fh1 4cd",
"category": "ELEC",
"priority": "P2",
"reported": "02/03/2026 09:40",
"status": "open ",
"updated": "2026-03-02T09:40:00",
"tenant_name": "M. Bell",
"tenant_phone": "01632 960102"
}Three details of the script are worth copying into everything you write. The address of the API comes from a setting with a default, so the same code can later point at the real system. The token comes from the environment, and the script stops at once if it is missing. And the request has a timeout, which lesson 3 explains.
Read the answer before you trust it
That one repair already tells you a good deal. Write down what you see, because each point becomes a rule in lesson 4.
- The postcode is in lower case. Somebody typed it, so expect every variation.
- The status is
openwith a space after it. Comparing it withOpenwould fail. - The reported date is written day first, with no time zone. Read month first, the second of March becomes the third of February.
- The time of the last change is in a different format from the reported date. Two formats in one record usually mean two parts of the system wrote them.
- The category and priority are codes. Somebody at the customer must tell you what each code means.
- The tenant's name and phone number are there, although you agreed not to copy them. An API returns what it returns, and leaving fields out is your job.
- The answer says it is page 1 of 3. One request did not fetch everything.
You have looked at one record of ten. Before writing any rules, look at all of them, and ask the repairs manager about anything you cannot explain.
When access fails
A request can fail in several ways, and the status number tells you which. Each one needs a different response from you.
- 401 means the system does not know who you are. The token is missing, mistyped or expired. Trying again will not help. Check the token, then ask the owner.
- 403 means the system knows who you are and will not allow this request. The account lacks a permission. Ask the owner, and say exactly which request was refused.
- 404 means the address is wrong, or the record does not exist.
- 429 means you are sending requests too quickly. Wait, then try again more slowly.
- A status from 500 upwards means their system failed. Waiting and trying again often works. If it keeps failing, tell the owner what you sent and when.
When you report a failure to the customer, give the time, the request and the status, and never include the token.
Key takeaways
- A token is a secret: it goes in the environment or a secrets store, never in the code, a ticket or a chat message.
- Make one small request and read the whole answer before you write anything else.
- Real data is untidy; note every oddity you see, because each one becomes a rule later.
- Learn what the common failure statuses mean, because each one calls for a different action.
Try it
Change first_call.py so that it asks for page 3 and prints only the ref of each repair on that page. Before you run it, predict how many references it will print, using the page count from this lesson. Then set REPAIRS_TOKEN to a wrong value, run it again and note the status in the error. A good result prints the two references R-2209 and R-2210 with the right token, and fails with status 401 with the wrong one.
Official documentation
Written with AI and checked automatically. Nobody has run these steps by hand, and tools change, so a command may behave differently in the version you install. Spotted a mistake? Tell us.