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 /accounts with payload {} creates an account and returns a 2xx JSON object containing "id" (for example, {"id": "acc_1"}).
  • POST /accounts/{id}/credits with payload {"amount": <positive_int>} deposits credits into the account.
  • GET /accounts/{id}/balance (no request body) returns a 2xx JSON object containing "balance" (for example, {"balance": 250}).
  • POST /accounts/{id}/spend with 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:

  1. load_config(env): Read CREDIT_API_BASE_URL and CREDIT_API_KEY from env, trim surrounding whitespace, and strip any trailing / characters from the base URL. If either value is missing or empty after trimming, raise ConfigError naming every missing variable; otherwise return (base_url, api_key).
  2. urllib_transport(method, url, headers, body): Perform a single HTTP request using urllib.request with an explicit socket timeout and return (status_code, response_bytes) for both 2xx and 4xx/5xx HTTP responses.
  3. CreditClient(base_url, api_key, transport=urllib_transport): Implement create_account() -> str, add_credits(account_id, amount) -> None, get_balance(account_id) -> int, and spend_credits(account_id, amount) -> None. Percent-encode account_id (including /) when building URL paths. Validate amount as a positive integer (bool is invalid and raises ValueError). Raise ApiError (setting error.status to the HTTP code, or None on transport exceptions such as OSError or http.client.HTTPException) whenever a network failure, non-2xx status, non-JSON 2xx body (empty 2xx bodies count as {}), or missing/invalid "id" or "balance" field occurs—without leaking api_key in error text.
  4. run_workflow(client, top_up=100, spend=30, log=print) -> Dict: Validate upfront (before any network call) that top_up and spend are positive integers with spend <= top_up, raising ValueError otherwise. Then create an account, read its initial balance start, deposit top_up credits, fetch and log after_top_up, spend spend credits, and fetch and log final. Verify both transitions (after_top_up == start + top_up and final == start + top_up - spend), raising BalanceMismatch on any discrepancy, and return {"account_id": account_id, "start": start, "after_top_up": after_top_up, "final": final}.
  5. main(argv=None, env=None, transport=urllib_transport) -> int: Parse optional --top-up (default 100) and --spend (default 30) integer flags, load configuration from env (defaulting to os.environ), and execute run_workflow. Return 0 on success; on ConfigError, ApiError, BalanceMismatch, or ValueError, print a readable message to sys.stderr and return 1.

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_up and spend must be positive int values (excluding bool) satisfying 1 <= spend <= top_up; invalid values must raise ValueError before create_account is called.
  • Secret credentials must never be hardcoded or echoed into exception messages or logs.
  • Runtime balance checks must raise BalanceMismatch explicitly rather than relying on Python assert statements.

Step-by-step walkthrough

  1. 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:

    1. Click each request and record its method (GET or POST), full URL (base URL + endpoint path), request headers (for example Authorization: Bearer <key> or X-API-Key: <key>), and JSON request body.
    2. Inspect the status code and JSON response body on success (200 OK or 201 Created).
    3. 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
    
  2. Load configuration without hardcoding secrets

    Hardcoding an API key in source code leaks it into Git history, and passing --api-key on 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 env as a dictionary parameter instead of reading os.environ directly inside load_config. That makes load_config a 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 produce https://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
    
  3. Isolate raw HTTP calls behind an injectable transport

    If our client called urllib.request.urlopen directly inside every method, testing error cases like 401 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.urlopen has two quirks we handle right here:

    1. No default timeout: Without timeout=10, a hung server blocks the script forever.
    2. 4xx and 5xx raise HTTPError: urlopen treats non-2xx statuses as exceptions, even though HTTPError still carries the status code (error.code) and the server's JSON explanation (error.read()). Catching HTTPError, 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()
    
  4. 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 clear ApiError.

    Notice how many things can go wrong on a real network, and how _request translates each one into a human-readable message without ever printing self.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.HTTPException alongside OSError? If a server closes the connection mid-download, response.read() raises http.client.IncompleteRead, which inherits from HTTPException, not OSError. 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]
    
  5. Build thin, reusable endpoint methods on `CreditClient`

    Once _request handles transport and JSON parsing, each API operation on CreditClient becomes 3–6 lines of self-explanatory code. Any other script (a batch top-up tool or an integration test) can import CreditClient and 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_id before calling str(raw_id) prevents {"id": null} from silently becoming the string "None" and calling /accounts/None/balance.
    • Guard against bool when checking numbers: In Python, bool is a subclass of int (isinstance(True, int) is True!). We check isinstance(..., bool) first in both _check_amount and get_balance, and math.isfinite rejects NaN or Inf.
    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})
    
  6. Orchestrate the workflow and validate every balance transition

    run_workflow executes the business steps in order. Three deliberate choices make its validation trustworthy:

    1. Validate top_up and spend before any network call. If someone passes top_up=25, spend=40 or spend=-5, we raise ValueError immediately rather than creating an unused account on the server first.
    2. Read start instead of assuming 0. Some sandboxes grant new accounts a promotional starter balance (say 15 credits). Reading start = client.get_balance(account_id) means start + top_up and start + top_up - spend stay exact either way.
    3. Use an explicit exception (BalanceMismatch), never assert. Python strips assert statements when invoked with python -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 140
    
    from 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,
        }
    
  7. Wire up the CLI entry point and trace a full run

    main parses --top-up and --spend, builds CreditClient from environment variables, and catches expected errors so the user gets a clean one-line message on stderr and exit code 1 (instead of an uncaught stack trace). Accepting argv, env, and transport as optional arguments makes main just 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: 0
    

    If the API key is invalid, step 1 returns 401 {"error": "invalid API key"}, the workflow stops immediately without attempting steps 2–6, prints error: POST /accounts returned HTTP 401: invalid API key to stderr, and exits with code 1.

  8. 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=10 bounds 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 15 credits): reading start first means the workflow expects 15 + 120 = 135 and 15 + 120 - 45 = 90 instead of failing against a hardcoded 75.
  • Empty 2xx response bodies (such as 204 No Content): _request returns {} cleanly for add_credits and spend_credits, while create_account and get_balance fail with a clear missing-field ApiError rather than a JSONDecodeError.
  • Null or blank account IDs ({"id": null} or {"id": " "}): rejected immediately by create_account instead of turning None into "None" and requesting /accounts/None/balance.
  • HTML error pages from proxies or load balancers (502 / 503): _error_message falls 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() raises http.client.IncompleteRead (an HTTPException, not an OSError), which _request catches and wraps in ApiError.
  • Special characters in account_id: URL percent-encoding (replacing characters like / or ? with %2F or %3F via urllib.parse.quote(..., safe="")) prevents an unusual ID from changing the URL path.
  • Invalid amounts (0, negatives, floats, True, or spend > top_up): rejected with ValueError before create_account is called, and isinstance(value, bool) is checked first because bool subclasses int in 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 401 or 500 response, blindly calling json.loads and indexing data["balance"] hides the server's actual error message behind a KeyError or JSONDecodeError.
  • Omitting socket timeouts: Python's urlopen (and third-party requests) waits forever by default if a server accepts a TCP connection and never replies.
  • Using assert for runtime validation: running python -O removes assert statements completely, so assert final == expected silently stops checking balances; raise an explicit BalanceMismatch exception instead.
  • Blindly retrying failed POST calls: if a POST /spend times out while reading the reply, the server may have already deducted the credits, so retrying without safeguards charges the account twice.

Alternative approaches

  • requests or httpx with a Session / 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 _request wrapper anyway, because response.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, and 504, 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 /balance is naturally safe to retry because reading does not change state. For POST calls, attach an idempotency key (a unique client-generated UUID sent in an Idempotency-Key header 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 FakeCreditApi on 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 runs main() against the live sandbox only when CREDIT_API_BASE_URL and CREDIT_API_KEY secrets 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 - spend no longer holds when another worker spends credits in between your POST and GET. Instead, validate each individual transaction receipt returned by POST /spend, and never enforce overdraft protection by calling get_balance on the client before spend_credits (two workers could both read 250 and both spend 180). Overdraft checks must happen on the server inside an atomic database update (a single indivisible operation such as UPDATE accounts SET balance = balance - 180 WHERE id = ? AND balance >= 180) that returns 409 Conflict if zero rows matched.

Follow-up questions

Similar questions

More Profound interview questions

All 1 Profound questions →