Credit Balance API Client Workflow
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
You are integrating with an HTTP credit-ledger service that exposes four JSON endpoints for managing prepaid customer accounts:
POST /accountswith payload{}creates an account and returns a2xxJSON object containing"id"(for example,{"id": "acc_1"}).POST /accounts/{id}/creditswith payload{"amount": <positive_int>}deposits credits into the account.GET /accounts/{id}/balance(no request body) returns a2xxJSON object containing"balance"(for example,{"balance": 250}).POST /accounts/{id}/spendwith payload{"amount": <positive_int>}deducts credits from the account.
Every request authenticates with an Authorization: Bearer <api_key> header and sends Accept: application/json (plus Content-Type: application/json whenever a JSON body is present). Non-2xx responses indicate errors and typically return JSON such as {"error": "..."} (or "message" / "detail"), though upstream proxies may return plain text or HTML.
Implement the reusable client library and command-line workflow declared in starter.py:
load_config(env): ReadCREDIT_API_BASE_URLandCREDIT_API_KEYfromenv, trim surrounding whitespace, and strip any trailing/characters from the base URL. If either value is missing or empty after trimming, raiseConfigErrornaming every missing variable; otherwise return(base_url, api_key).urllib_transport(method, url, headers, body): Perform a single HTTP request usingurllib.requestwith an explicit socket timeout and return(status_code, response_bytes)for both2xxand4xx/5xxHTTP responses.CreditClient(base_url, api_key, transport=urllib_transport): Implementcreate_account() -> str,add_credits(account_id, amount) -> None,get_balance(account_id) -> int, andspend_credits(account_id, amount) -> None. Percent-encodeaccount_id(including/) when building URL paths. Validateamountas a positive integer (boolis invalid and raisesValueError). RaiseApiError(settingerror.statusto the HTTP code, orNoneon transport exceptions such asOSErrororhttp.client.HTTPException) whenever a network failure, non-2xxstatus, non-JSON2xxbody (empty2xxbodies count as{}), or missing/invalid"id"or"balance"field occurs—without leakingapi_keyin error text.run_workflow(client, top_up=100, spend=30, log=print) -> Dict: Validate upfront (before any network call) thattop_upandspendare positive integers withspend <= top_up, raisingValueErrorotherwise. Then create an account, read its initial balancestart, deposittop_upcredits, fetch and logafter_top_up, spendspendcredits, and fetch and logfinal. Verify both transitions (after_top_up == start + top_upandfinal == start + top_up - spend), raisingBalanceMismatchon any discrepancy, and return{"account_id": account_id, "start": start, "after_top_up": after_top_up, "final": final}.main(argv=None, env=None, transport=urllib_transport) -> int: Parse optional--top-up(default100) and--spend(default30) integer flags, load configuration fromenv(defaulting toos.environ), and executerun_workflow. Return0on success; onConfigError,ApiError,BalanceMismatch, orValueError, print a readable message tosys.stderrand return1.
Examples
Example 1
Input: run_workflow(client, top_up=250, spend=95) against a sandbox where new accounts start at 0 credits.
Output:
{"account_id": "acc_1", "start": 0, "after_top_up": 250, "final": 155}
Walk-through: The client creates "acc_1", reads start = 0, deposits 250 credits and confirms after_top_up = 250 == 0 + 250, then spends 95 credits and confirms final = 155 == 0 + 250 - 95, logging both observed balances.
Example 2
Input: run_workflow(client, top_up=120, spend=45) against a sandbox that grants every new account a 15-credit starter balance.
Output:
{"account_id": "acc_1", "start": 15, "after_top_up": 135, "final": 90}
Walk-through: Because run_workflow queries the initial balance (15) before depositing credits, it expects 15 + 120 = 135 after the deposit and 15 + 120 - 45 = 90 after the debit, so both checks succeed.
Example 3
Input: run_workflow(client, top_up=200, spend=60) against a buggy server that deducts every spend request twice.
Output: Raises BalanceMismatch reporting actual closing balance 80 versus expected 140.
Walk-through: After depositing 200 credits (after_top_up = 200), the server subtracts 2 * 60 = 120 during spend_credits, leaving 80 instead of 0 + 200 - 60 = 140.
Constraints
- Only the Python standard library may be used (
urllib,http.client,json,argparse,os,sys). top_upandspendmust be positiveintvalues (excludingbool) satisfying1 <= spend <= top_up; invalid values must raiseValueErrorbeforecreate_accountis called.- Secret credentials must never be hardcoded or echoed into exception messages or logs.
- Runtime balance checks must raise
BalanceMismatchexplicitly rather than relying on Pythonassertstatements.
Step-by-step walkthrough
Pin down the API contract from the docs or browser Network tab
Before writing a single line of Python, we need the exact wire contract: which URLs to call, which HTTP methods they expect, how the API key is sent, and what JSON comes back. When a documentation page only gives runnable "Try It" buttons, open the browser's developer tools, switch to the Network tab, and click through each action once:
- Click each request and record its method (
GETorPOST), full URL (base URL + endpoint path), request headers (for exampleAuthorization: Bearer <key>orX-API-Key: <key>), and JSON request body. - Inspect the status code and JSON response body on success (
200 OKor201 Created). - Trigger one failure on purpose (such as spending more credits than you have) to see how the server formats errors.
Keeping the entire contract in one table at the top of the file makes it trivial to adapt if a field name differs in the real sandbox:
Operation Method & Path Request JSON Success Response -------------- ----------------------------- ---------------- -------------------------- Create account POST /accounts {} 201 {"id": "acc_1", ...} Add credits POST /accounts/{id}/credits {"amount": 250} 200 {"balance": 250} Read balance GET /accounts/{id}/balance (none) 200 {"balance": 250} Spend credits POST /accounts/{id}/spend {"amount": 95} 200 {"balance": 155} Auth header: Authorization: Bearer <API key> Error format: non-2xx HTTP status with JSON {"error": "..."} (or HTML from a proxy)We will organize the program into five small layers so each piece has one job:
main() --> load_config() --> run_workflow() --> CreditClient --> transport() CLI args env variables business checks API endpoints raw HTTP call- Click each request and record its method (
Load configuration without hardcoding secrets
Hardcoding an API key in source code leaks it into Git history, and passing
--api-keyon the command line exposes it in shell history and process listings (ps). Reading both the base URL and the API key from environment variables avoids both traps and works identically on a laptop, in CI secrets, and in containers.Two details save debugging time for beginners and production users alike:
- Pass
envas a dictionary parameter instead of readingos.environdirectly insideload_config. That makesload_configa pure function we can unit-test with plain Python dicts. - Normalize and report all missing variables at once. Copy-pasting keys often leaves a trailing newline, and copy-pasting base URLs often leaves a trailing
/(which would later producehttps://host/v1//accounts). Stripping whitespace and trailing slashes up front prevents both bugs, and listing every missing variable lets the user fix configuration in one shot.
from typing import Dict, List, Tuple BASE_URL_ENV = "CREDIT_API_BASE_URL" API_KEY_ENV = "CREDIT_API_KEY" class ConfigError(Exception): """The base URL or the API key is not configured.""" def load_config(env: Dict[str, str]) -> Tuple[str, str]: """Return (base_url without a trailing slash, api_key) from environment variables.""" # Strip whitespace and trailing slashes first so "/" or " " is caught as missing base_url = env.get(BASE_URL_ENV, "").strip().rstrip("/") api_key = env.get(API_KEY_ENV, "").strip() # Collect every missing variable so the user can fix all of them in one pass missing: List[str] = [] if not base_url: missing.append(BASE_URL_ENV) if not api_key: missing.append(API_KEY_ENV) if missing: raise ConfigError("missing environment variable(s): " + ", ".join(missing)) return base_url, api_key- Pass
Isolate raw HTTP calls behind an injectable transport
If our client called
urllib.request.urlopendirectly inside every method, testing error cases like401 Unauthorized,409 Conflict, or a dropped connection would require spinning up a real HTTP server. Instead, we put all network I/O behind one small function signature:transport(method, url, headers, body) -> (status, response_bytes).Python's
urllib.request.urlopenhas two quirks we handle right here:- No default timeout: Without
timeout=10, a hung server blocks the script forever. - 4xx and 5xx raise
HTTPError:urlopentreats non-2xx statuses as exceptions, even thoughHTTPErrorstill carries the status code (error.code) and the server's JSON explanation (error.read()). CatchingHTTPError, reading its body, and closing its socket turns every HTTP response into a clean(status, body_bytes)tuple.
from typing import Callable, Dict, Optional, Tuple import urllib.error import urllib.request # Transport: function(method, full_url, headers, raw_body_bytes) -> (http_status, response_bytes) Transport = Callable[[str, str, Dict[str, str], Optional[bytes]], Tuple[int, bytes]] def urllib_transport(method: str, url: str, headers: Dict[str, str], body: Optional[bytes]) -> Tuple[int, bytes]: """Send one request with the standard library; return (status, body) for any HTTP status.""" request = urllib.request.Request(url, data=body, headers=headers, method=method) try: # timeout=10 prevents a stalled server from hanging the script indefinitely with urllib.request.urlopen(request, timeout=10) as response: return response.status, response.read() except urllib.error.HTTPError as error: # urlopen raises HTTPError on 4xx/5xx; read the error body and close the socket try: return error.code, error.read() finally: error.close()- No default timeout: Without
Centralize headers, JSON parsing, and error handling in `_request`
Every endpoint needs the same plumbing: attach the
Authorization: Bearer <key>header, JSON-encode any request payload, check the status code before parsing the body as data, and turn any failure into one clearApiError.Notice how many things can go wrong on a real network, and how
_requesttranslates each one into a human-readable message without ever printingself.api_key:Failure mode Resulting ApiError ----------------------------------- --------------------------------------------------------------- DNS / refused socket (OSError) POST /accounts: network error: connection refused (status=None) Cut-off stream (IncompleteRead) GET /accounts/acc_1/balance: network error: IncompleteRead(...) 401 / 409 JSON error POST /accounts returned HTTP 401: invalid API key (status=401) 502 HTML gateway page POST /accounts returned HTTP 502: <html>Bad Gateway... (status=502) 200 OK with non-JSON text GET /accounts/acc_1/balance: response is not JSON: OK 201 Created missing expected field POST /accounts: response has no 'id' field: {'name': 'acc'}Why catch
http.client.HTTPExceptionalongsideOSError? If a server closes the connection mid-download,response.read()raiseshttp.client.IncompleteRead, which inherits fromHTTPException, notOSError. Catching both guarantees no raw socket traceback escapes.from typing import Dict, Optional import http.client import json class ApiError(Exception): """A request failed: network error, non-2xx status, or a response we cannot read.""" def __init__(self, message: str, status: Optional[int] = None) -> None: super().__init__(message) # status holds the HTTP status code (e.g. 401, 409), or None for network errors self.status = status def _error_message(text: str) -> str: """Extract a short readable message from an error body (JSON error field or raw text).""" try: data = json.loads(text) except ValueError: data = None # Prefer common JSON error fields when they contain a non-empty value if isinstance(data, dict): for key in ("error", "message", "detail"): value = data.get(key) if value is not None and str(value).strip(): return str(value) cleaned = text.strip() if not cleaned: return "(empty body)" # Cap raw HTML/text error bodies (such as 502 proxy pages) at 200 characters return cleaned[:200] def _require(data: Dict, field: str, where: str): """Return data[field], or raise ApiError if the JSON object is missing that key.""" if field not in data: raise ApiError(f"{where}: response has no '{field}' field: {data}") return data[field]Build thin, reusable endpoint methods on `CreditClient`
Once
_requesthandles transport and JSON parsing, each API operation onCreditClientbecomes 3–6 lines of self-explanatory code. Any other script (a batch top-up tool or an integration test) can importCreditClientand call these methods directly.Three defensive checks protect callers from subtle Python and HTTP pitfalls:
- Escape account IDs in URL paths:
urllib.parse.quote(account_id, safe="")percent-encodes characters like/or?so a strange account ID cannot alter which URL path is hit. - Reject null or blank account IDs: Checking
raw_idbefore callingstr(raw_id)prevents{"id": null}from silently becoming the string"None"and calling/accounts/None/balance. - Guard against
boolwhen checking numbers: In Python,boolis a subclass ofint(isinstance(True, int)isTrue!). We checkisinstance(..., bool)first in both_check_amountandget_balance, andmath.isfiniterejectsNaNorInf.
import math import urllib.parse def _check_amount(name: str, value: int) -> None: """Ensure a credit amount is a positive integer (rejecting bool, which subclasses int).""" if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise ValueError(f"{name} must be a positive integer, got {value!r}") class CreditClient: """One method per API operation. The transport is injectable so tests need no network.""" def __init__(self, base_url: str, api_key: str, transport: Transport = urllib_transport) -> None: self.base_url = base_url.rstrip("/") self.api_key = api_key self.transport = transport def _request(self, method: str, path: str, payload: Optional[Dict] = None) -> Dict: """Send one API request and return the parsed JSON dict, or raise ApiError.""" headers = { "Authorization": "Bearer " + self.api_key, "Accept": "application/json", } body: Optional[bytes] = None if payload is not None: body = json.dumps(payload).encode("utf-8") headers["Content-Type"] = "application/json" where = f"{method} {path}" full_url = self.base_url + path try: status, raw = self.transport(method, full_url, headers, body) except (OSError, http.client.HTTPException) as error: raise ApiError(f"{where}: network error: {error}") from error text = raw.decode("utf-8", errors="replace") if status < 200 or status >= 300: reason = _error_message(text) raise ApiError(f"{where} returned HTTP {status}: {reason}", status) if not text.strip(): return {} try: data = json.loads(text) except ValueError: raise ApiError(f"{where}: response is not JSON: {text[:200]}", status) from None if not isinstance(data, dict): raise ApiError(f"{where}: expected a JSON object, got: {text[:200]}", status) return data def _account_path(self, account_id: str, action: str) -> str: """Build /accounts/<escaped_id>/<action> safely even if account_id has '/' or '?'.""" escaped_id = urllib.parse.quote(account_id, safe="") return f"/accounts/{escaped_id}/{action}" def create_account(self) -> str: """Create an account and return its id.""" data = self._request("POST", "/accounts", {}) raw_id = _require(data, "id", "POST /accounts") # Reject null, boolean, or blank IDs instead of turning None into "None" if isinstance(raw_id, bool) or not isinstance(raw_id, (str, int)) or not str(raw_id).strip(): raise ApiError(f"POST /accounts: invalid 'id' field: {raw_id!r}") return str(raw_id) def add_credits(self, account_id: str, amount: int) -> None: """Add `amount` credits to the account.""" _check_amount("amount", amount) path = self._account_path(account_id, "credits") self._request("POST", path, {"amount": amount}) def get_balance(self, account_id: str) -> int: """Return the account's current balance.""" path = self._account_path(account_id, "balance") data = self._request("GET", path) balance = _require(data, "balance", "GET " + path) # Reject booleans, strings, and non-finite floats (NaN / Inf) if isinstance(balance, bool) or not isinstance(balance, (int, float)) or not math.isfinite(balance): raise ApiError(f"GET {path}: balance is not a number: {balance!r}") return balance def spend_credits(self, account_id: str, amount: int) -> None: """Spend `amount` credits from the account.""" _check_amount("amount", amount) path = self._account_path(account_id, "spend") self._request("POST", path, {"amount": amount})- Escape account IDs in URL paths:
Orchestrate the workflow and validate every balance transition
run_workflowexecutes the business steps in order. Three deliberate choices make its validation trustworthy:- Validate
top_upandspendbefore any network call. If someone passestop_up=25, spend=40orspend=-5, we raiseValueErrorimmediately rather than creating an unused account on the server first. - Read
startinstead of assuming0. Some sandboxes grant new accounts a promotional starter balance (say15credits). Readingstart = client.get_balance(account_id)meansstart + top_upandstart + top_up - spendstay exact either way. - Use an explicit exception (
BalanceMismatch), neverassert. Python stripsassertstatements when invoked withpython -O, which would silently disable balance validation. Checking after both the top-up and the spend pinpoints exactly which step misbehaved:
Scenario Balances (start -> top_up -> final) Result ------------------------------ ----------------------------------- ------------------------------------------- Zero-balance new account 0 -> 250 -> 155 OK (155 == 0 + 250 - 95) 15-credit starter bonus 15 -> 135 -> 90 OK (90 == 15 + 120 - 45) Server bug double-charges spend 0 -> 200 -> 80 BalanceMismatch: final balance is 80, expected 140from typing import Callable, Dict class BalanceMismatch(Exception): """The API reports a different balance from the one the workflow expects.""" def _expect(label: str, expected: int, actual: int) -> None: """Raise BalanceMismatch if the server's balance differs from our expected value.""" if actual != expected: raise BalanceMismatch(f"{label} balance is {actual}, expected {expected}") def run_workflow(client: CreditClient, top_up: int = 100, spend: int = 30, log: Callable[[str], None] = print) -> Dict: """Create an account, add `top_up`, spend `spend`, and check both balances. Returns {"account_id", "start", "after_top_up", "final"}. Raises ValueError for bad amounts (before any request), ApiError for failed requests, BalanceMismatch for wrong balances. """ # Phase 1: validate inputs up front so bad numbers never leave an orphan account behind _check_amount("top_up", top_up) _check_amount("spend", spend) if spend > top_up: raise ValueError(f"spend ({spend}) must not exceed top_up ({top_up})") # Phase 2: create the account and read its initial balance instead of assuming 0 account_id = client.create_account() log(f"Created account {account_id}") start = client.get_balance(account_id) # Phase 3: add credits and verify the intermediate balance immediately client.add_credits(account_id, top_up) after_top_up = client.get_balance(account_id) log(f"Balance after adding {top_up} credits: {after_top_up}") _expect("after top-up", start + top_up, after_top_up) # Phase 4: spend credits and verify the final balance client.spend_credits(account_id, spend) final = client.get_balance(account_id) log(f"Balance after spending {spend} credits: {final}") _expect("final", start + top_up - spend, final) log(f"OK: final balance {final} = {start} + {top_up} - {spend}") return { "account_id": account_id, "start": start, "after_top_up": after_top_up, "final": final, }- Validate
Wire up the CLI entry point and trace a full run
mainparses--top-upand--spend, buildsCreditClientfrom environment variables, and catches expected errors so the user gets a clean one-line message onstderrand exit code1(instead of an uncaught stack trace). Acceptingargv,env, andtransportas optional arguments makesmainjust as easy to unit-test as every helper below it.Let's trace the six HTTP calls made during Example 1 (
top_up=250,spend=95):Step HTTP Request Server Response Console Output ---- --------------------------------------------- ------------------------- ----------------------------------------- 1 POST /accounts {} 201 {"id": "acc_1"} Created account acc_1 2 GET /accounts/acc_1/balance 200 {"balance": 0} (records start = 0) 3 POST /accounts/acc_1/credits {"amount": 250} 200 {"balance": 250} 4 GET /accounts/acc_1/balance 200 {"balance": 250} Balance after adding 250 credits: 250 5 POST /accounts/acc_1/spend {"amount": 95} 200 {"balance": 155} 6 GET /accounts/acc_1/balance 200 {"balance": 155} Balance after spending 95 credits: 155 OK: final balance 155 = 0 + 250 - 95 Process exit code: 0If the API key is invalid, step 1 returns
401 {"error": "invalid API key"}, the workflow stops immediately without attempting steps 2–6, printserror: POST /accounts returned HTTP 401: invalid API keytostderr, and exits with code1.Complete solution
from typing import Callable, Dict, List, Optional, Tuple import argparse import http.client import json import math import os import sys import urllib.error import urllib.parse import urllib.request # Assumed REST API contract (verify in documentation or browser Network tab): # POST /accounts {} -> 201 {"id": "acc_1", ...} # POST /accounts/{id}/credits {"amount": 100} -> 200 {"balance": 100} # GET /accounts/{id}/balance -> 200 {"balance": 100} # POST /accounts/{id}/spend {"amount": 30} -> 200 {"balance": 70} # errors: non-2xx status, usually with a JSON body such as {"error": "..."} # auth: header Authorization: Bearer <API key> BASE_URL_ENV = "CREDIT_API_BASE_URL" API_KEY_ENV = "CREDIT_API_KEY" # Transport: function(method, full_url, headers, raw_body_bytes) -> (http_status, response_bytes) Transport = Callable[[str, str, Dict[str, str], Optional[bytes]], Tuple[int, bytes]] class ConfigError(Exception): """The base URL or the API key is not configured.""" class ApiError(Exception): """A request failed: network error, non-2xx status, or a response we cannot read.""" def __init__(self, message: str, status: Optional[int] = None) -> None: super().__init__(message) # status holds the HTTP status code (e.g. 401, 409), or None for network errors self.status = status class BalanceMismatch(Exception): """The API reports a different balance from the one the workflow expects.""" def load_config(env: Dict[str, str]) -> Tuple[str, str]: """Return (base_url without a trailing slash, api_key) from environment variables.""" # Strip whitespace and trailing slashes first so "/" or " " is caught as missing base_url = env.get(BASE_URL_ENV, "").strip().rstrip("/") api_key = env.get(API_KEY_ENV, "").strip() # Collect every missing variable so the user can fix all of them in one pass missing: List[str] = [] if not base_url: missing.append(BASE_URL_ENV) if not api_key: missing.append(API_KEY_ENV) if missing: raise ConfigError("missing environment variable(s): " + ", ".join(missing)) return base_url, api_key def urllib_transport(method: str, url: str, headers: Dict[str, str], body: Optional[bytes]) -> Tuple[int, bytes]: """Send one request with the standard library; return (status, body) for any HTTP status.""" request = urllib.request.Request(url, data=body, headers=headers, method=method) try: # timeout=10 prevents a stalled server from hanging the script indefinitely with urllib.request.urlopen(request, timeout=10) as response: return response.status, response.read() except urllib.error.HTTPError as error: # urlopen raises HTTPError on 4xx/5xx; read the error body and close the socket try: return error.code, error.read() finally: error.close() def _error_message(text: str) -> str: """Extract a short readable message from an error body (JSON error field or raw text).""" try: data = json.loads(text) except ValueError: data = None # Prefer common JSON error fields when they contain a non-empty value if isinstance(data, dict): for key in ("error", "message", "detail"): value = data.get(key) if value is not None and str(value).strip(): return str(value) cleaned = text.strip() if not cleaned: return "(empty body)" # Cap raw HTML/text error bodies (such as 502 proxy pages) at 200 characters return cleaned[:200] def _require(data: Dict, field: str, where: str): """Return data[field], or raise ApiError if the JSON object is missing that key.""" if field not in data: raise ApiError(f"{where}: response has no '{field}' field: {data}") return data[field] def _check_amount(name: str, value: int) -> None: """Ensure a credit amount is a positive integer (rejecting bool, which subclasses int).""" if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise ValueError(f"{name} must be a positive integer, got {value!r}") class CreditClient: """One method per API operation. The transport is injectable so tests need no network.""" def __init__(self, base_url: str, api_key: str, transport: Transport = urllib_transport) -> None: self.base_url = base_url.rstrip("/") self.api_key = api_key self.transport = transport def _request(self, method: str, path: str, payload: Optional[Dict] = None) -> Dict: """Send one API request and return the parsed JSON dict, or raise ApiError.""" # Attach bearer authentication without ever logging self.api_key in error messages headers = { "Authorization": "Bearer " + self.api_key, "Accept": "application/json", } body: Optional[bytes] = None if payload is not None: body = json.dumps(payload).encode("utf-8") headers["Content-Type"] = "application/json" where = f"{method} {path}" full_url = self.base_url + path # Phase 1: send over the wire and catch both socket errors and dropped connections try: status, raw = self.transport(method, full_url, headers, body) except (OSError, http.client.HTTPException) as error: raise ApiError(f"{where}: network error: {error}") from error # Phase 2: check HTTP status before trying to parse the response as success JSON text = raw.decode("utf-8", errors="replace") if status < 200 or status >= 300: reason = _error_message(text) raise ApiError(f"{where} returned HTTP {status}: {reason}", status) # Phase 3: decode JSON object (allow empty 2xx bodies such as 204 No Content) if not text.strip(): return {} try: data = json.loads(text) except ValueError: raise ApiError(f"{where}: response is not JSON: {text[:200]}", status) from None if not isinstance(data, dict): raise ApiError(f"{where}: expected a JSON object, got: {text[:200]}", status) return data def _account_path(self, account_id: str, action: str) -> str: """Build /accounts/<escaped_id>/<action> safely even if account_id has '/' or '?'.""" escaped_id = urllib.parse.quote(account_id, safe="") return f"/accounts/{escaped_id}/{action}" def create_account(self) -> str: """Create an account and return its id.""" data = self._request("POST", "/accounts", {}) raw_id = _require(data, "id", "POST /accounts") # Reject null, boolean, or blank IDs instead of turning None into "None" if isinstance(raw_id, bool) or not isinstance(raw_id, (str, int)) or not str(raw_id).strip(): raise ApiError(f"POST /accounts: invalid 'id' field: {raw_id!r}") return str(raw_id) def add_credits(self, account_id: str, amount: int) -> None: """Add `amount` credits to the account.""" _check_amount("amount", amount) path = self._account_path(account_id, "credits") self._request("POST", path, {"amount": amount}) def get_balance(self, account_id: str) -> int: """Return the account's current balance.""" path = self._account_path(account_id, "balance") data = self._request("GET", path) balance = _require(data, "balance", "GET " + path) # Reject booleans, strings, and non-finite floats (NaN / Inf) if isinstance(balance, bool) or not isinstance(balance, (int, float)) or not math.isfinite(balance): raise ApiError(f"GET {path}: balance is not a number: {balance!r}") return balance def spend_credits(self, account_id: str, amount: int) -> None: """Spend `amount` credits from the account.""" _check_amount("amount", amount) path = self._account_path(account_id, "spend") self._request("POST", path, {"amount": amount}) def _expect(label: str, expected: int, actual: int) -> None: """Raise BalanceMismatch if the server's balance differs from our expected value.""" if actual != expected: raise BalanceMismatch(f"{label} balance is {actual}, expected {expected}") def run_workflow(client: CreditClient, top_up: int = 100, spend: int = 30, log: Callable[[str], None] = print) -> Dict: """Create an account, add `top_up`, spend `spend`, and check both balances. Returns {"account_id", "start", "after_top_up", "final"}. Raises ValueError for bad amounts (before any request), ApiError for failed requests, BalanceMismatch for wrong balances. """ # Phase 1: validate inputs up front so bad numbers never leave an orphan account behind _check_amount("top_up", top_up) _check_amount("spend", spend) if spend > top_up: raise ValueError(f"spend ({spend}) must not exceed top_up ({top_up})") # Phase 2: create the account and read its initial balance instead of assuming 0 account_id = client.create_account() log(f"Created account {account_id}") start = client.get_balance(account_id) # Phase 3: add credits and verify the intermediate balance immediately client.add_credits(account_id, top_up) after_top_up = client.get_balance(account_id) log(f"Balance after adding {top_up} credits: {after_top_up}") _expect("after top-up", start + top_up, after_top_up) # Phase 4: spend credits and verify the final balance client.spend_credits(account_id, spend) final = client.get_balance(account_id) log(f"Balance after spending {spend} credits: {final}") _expect("final", start + top_up - spend, final) log(f"OK: final balance {final} = {start} + {top_up} - {spend}") return { "account_id": account_id, "start": start, "after_top_up": after_top_up, "final": final, } def main(argv: Optional[List[str]] = None, env: Optional[Dict[str, str]] = None, transport: Transport = urllib_transport) -> int: """Command-line entry point. Returns the process exit code: 0 on success, 1 on any failure.""" parser = argparse.ArgumentParser(description="Run the credit API workflow end to end.") parser.add_argument("--top-up", type=int, default=100, help="credits to add (default 100)") parser.add_argument("--spend", type=int, default=30, help="credits to spend (default 30)") args = parser.parse_args(argv) if env is None: env = dict(os.environ) # Convert expected configuration, network, API, and validation failures into exit code 1 try: base_url, api_key = load_config(env) client = CreditClient(base_url, api_key, transport) run_workflow(client, args.top_up, args.spend) except (ConfigError, ApiError, BalanceMismatch, ValueError) as error: print(f"error: {error}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": sys.exit(main())✅ Submit now — all tests should pass.
Intuition & how it works
Think of building an API workflow like writing an automated teller machine (ATM) test script: you open a fresh test account, deposit 250 dollars, check the receipt, withdraw 95 dollars, and verify the receipt says 155 dollars. A RESTful API (an HTTP service where URLs name resources like /accounts and HTTP verbs like GET and POST describe actions) works the same way, using a bearer token (a secret string sent in the Authorization: Bearer <key> header to prove who is calling).
A quick throwaway script usually pastes the API key straight into the file, calls urlopen four times in a row with copy-pasted headers, parses .json() without checking the HTTP status code first, and hardcodes assert balance == 155. That naive script leaks secrets into Git, hangs forever if the network stalls, crashes with a cryptic JSONDecodeError when a proxy returns an HTML 502 Bad Gateway page, and silently skips validation when Python runs with -O (which strips assert statements). Instead, we separate configuration, raw HTTP transport (dependency injection, meaning we pass the network function into the client so tests can swap in an in-memory fake), reusable client methods, and business validation.
Walk through Example 1 with top_up = 250 and spend = 95 on an account whose initial balance is 0:
1. load_config reads CREDIT_API_BASE_URL and CREDIT_API_KEY from the environment, stripping stray whitespace and trailing slashes.
2. run_workflow checks top_up > 0, spend > 0, and spend <= top_up before sending any network traffic.
3. POST /accounts creates "acc_1", and GET /accounts/acc_1/balance reads start = 0.
4. POST /accounts/acc_1/credits adds 250, and GET /accounts/acc_1/balance confirms after_top_up = 250 == 0 + 250.
5. POST /accounts/acc_1/spend deducts 95, and GET /accounts/acc_1/balance confirms final = 155 == 0 + 250 - 95.
Complexity
- Time: O(1) CPU work and exactly 6 HTTP round trips. Each workflow run performs a fixed sequence of six API calls (
create_account,get_balance,add_credits,get_balance,spend_credits,get_balance), doing constant-time JSON encoding and decoding per call. At 100 ms per network round trip, a successful run finishes in roughly 0.6 seconds;timeout=10bounds each individual socket connect or read operation so a dead server cannot hang indefinitely. - Space: O(B), where B is the byte size of the largest single HTTP response body. Only one response body is held in memory and parsed at a time before being discarded, and raw error snippets are truncated to at most 200 characters.
Edge cases
- Non-zero starting balance (such as Example 2's starter bonus of
15credits): readingstartfirst means the workflow expects15 + 120 = 135and15 + 120 - 45 = 90instead of failing against a hardcoded75. - Empty 2xx response bodies (such as
204 No Content):_requestreturns{}cleanly foradd_creditsandspend_credits, whilecreate_accountandget_balancefail with a clear missing-fieldApiErrorrather than aJSONDecodeError. - Null or blank account IDs (
{"id": null}or{"id": " "}): rejected immediately bycreate_accountinstead of turningNoneinto"None"and requesting/accounts/None/balance. - HTML error pages from proxies or load balancers (
502/503):_error_messagefalls back from JSON fields (error,message,detail) to the first 200 characters of raw text alongside the HTTP status code. - Connections cut off mid-response:
response.read()raiseshttp.client.IncompleteRead(anHTTPException, not anOSError), which_requestcatches and wraps inApiError. - Special characters in
account_id: URL percent-encoding (replacing characters like/or?with%2For%3Fviaurllib.parse.quote(..., safe="")) prevents an unusual ID from changing the URL path. - Invalid amounts (
0, negatives, floats,True, orspend > top_up): rejected withValueErrorbeforecreate_accountis called, andisinstance(value, bool)is checked first becauseboolsubclassesintin Python.
Common mistakes
- Hardcoding API keys in source code or logging request headers: secrets belong in environment variables and must never appear in error messages or logs.
- Parsing JSON before checking the HTTP status code: on a
401or500response, blindly callingjson.loadsand indexingdata["balance"]hides the server's actual error message behind aKeyErrororJSONDecodeError. - Omitting socket timeouts: Python's
urlopen(and third-partyrequests) waits forever by default if a server accepts a TCP connection and never replies. - Using
assertfor runtime validation: runningpython -Oremovesassertstatements completely, soassert final == expectedsilently stops checking balances; raise an explicitBalanceMismatchexception instead. - Blindly retrying failed
POSTcalls: if aPOST /spendtimes out while reading the reply, the server may have already deducted the credits, so retrying without safeguards charges the account twice.
Alternative approaches
requestsorhttpxwith aSession/Client: third-party HTTP libraries make JSON requests concise and reuse a single TCP/TLS connection across all six calls (HTTP keep-alive), cutting latency in half. Keep a central_requestwrapper anyway, becauseresponse.raise_for_status()omits the server's JSON error message by default.- Generated client from an OpenAPI specification: if the provider publishes an OpenAPI schema, code generation guarantees exact endpoint paths and payload types automatically, trading off an extra build step and generated boilerplate.
Follow-up questions
- How can the client retry transient network failures without double-crediting or double-charging an account? Only retry transient failures such as network timeouts,
429 Too Many Requests,502,503, and504, using exponential backoff with jitter (doubling the wait time between attempts, such as 0.5 s, 1 s, 2 s, plus a small random offset so retrying clients do not all hit the server at the exact same instant).GET /balanceis naturally safe to retry because reading does not change state. ForPOSTcalls, attach an idempotency key (a unique client-generated UUID sent in anIdempotency-Keyheader so the server recognizes retries of the same operation and applies it at most once); if the API does not support idempotency keys, query the balance or transaction history before deciding whether to retry. - How would you structure continuous integration so both offline unit checks and live sandbox checks stay reliable? Keep the fast, deterministic unit tests backed by
FakeCreditApion every commit and pull request so every error branch (401,409,500, dropped sockets) runs in milliseconds offline. Add a separate scheduled smoke test that runsmain()against the live sandbox only whenCREDIT_API_BASE_URLandCREDIT_API_KEYsecrets are configured, creating a fresh account per run so parallel jobs never step on each other's balances. - How does balance verification change if several processes debit the same credit account at the same time? The client-side formula
final == start + top_up - spendno longer holds when another worker spends credits in between yourPOSTandGET. Instead, validate each individual transaction receipt returned byPOST /spend, and never enforce overdraft protection by callingget_balanceon the client beforespend_credits(two workers could both read250and both spend180). Overdraft checks must happen on the server inside an atomic database update (a single indivisible operation such asUPDATE accounts SET balance = balance - 180 WHERE id = ? AND balance >= 180) that returns409 Conflictif zero rows matched.
Follow-up questions
- How can the client retry transient network failures without double-crediting or double-charging an account?
- How would you structure continuous integration so both offline unit checks and live sandbox checks stay reliable?
- How does balance verification change if several processes debit the same credit account at the same time?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes