Python Master Course V2 — 100. Web and API Capstone: Inventory Service
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 09 — WEB AND API ENGINEERING · LESSON 100 / 200
Web and API Capstone: Inventory Service
Study time: 90–120 minutes. Prerequisites: HTTP, JSON, functions, exceptions and Lesson 99.
Video lesson
Video not yet available. This is a reserved space for a verified video URL/player.
Outcomes
Integrate routing, validation and persistence concepts. You should also be able to identify security implications, test expected and error behavior, and explain your design choices.
Detailed concepts
A reliable service separates request parsing, domain rules, repository operations and response serialization. Design HTTP status codes, pagination, authentication boundaries, idempotency and logging before deployment.
Professional API workflow: model the resource, define request and response schemas, validate inputs, enforce authorization, choose suitable status codes, set timeouts and resource limits, and test normal and failure scenarios. Treat all network data as untrusted. Avoid leaking credentials in logs, URLs or error responses.
Maintainability: separate transport code from business logic, document assumptions, use dependency injection for testable clients, and prefer bounded operations over unbounded retries or pagination loops.
Understand and apply: Web and API Capstone: Inventory Service
Build one complete local service before extending it
This capstone runs a real loopback-only HTTP service backed by SQLite. It supports a paginated product list, individual product lookup, an absolute quantity update and a paginated audit list. The fixture starts with PEN quantity ten. Updates accept only an integer from zero to one million; booleans are rejected. Every changed quantity and its audit row commit together.
The service uses Python’s standard-library HTTPServer for a small teaching application, not a production deployment. It binds only to 127.0.0.1. A fabricated practice-token demonstrates an authentication boundary without handling real secrets; every holder has the same demo permissions. Production identity, object-level authorization, TLS termination, robust HTTP hardening and deployment monitoring require a separate implementation.
Local execution: these two files need a normal desktop Python interpreter because they open a loopback listening socket and import a neighboring file. Copy and run them locally; the browser runner cannot execute this service.
Save the next block as inventory_service.py in a disposable practice folder. The factory creates the schema once and returns a server; each request opens and closes its own database connection. Reopening the same database file preserves committed changes. The automatic fixture insert does not reset an existing product on restart.
File: inventory_service.py
import json
import re
import sqlite3
from contextlib import closing
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlsplit
def make_server(database, port=8000):
with closing(sqlite3.connect(database)) as db:
db.executescript("""
CREATE TABLE IF NOT EXISTS products(
sku TEXT NOT NULL PRIMARY KEY,
qty INTEGER NOT NULL CHECK(typeof(qty) = 'integer' AND qty BETWEEN 0 AND 1000000));
CREATE TABLE IF NOT EXISTS movements(
id INTEGER PRIMARY KEY,
sku TEXT NOT NULL,
old_qty INTEGER NOT NULL,
new_qty INTEGER NOT NULL);
""")
with db:
db.execute("INSERT OR IGNORE INTO products VALUES (?, ?)", ("PEN", 10))
class Handler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
pass # Keep this practice server's console deterministic.
def reply(self, status, payload):
body = json.dumps(payload, sort_keys=True).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
if status == 401:
self.send_header("WWW-Authenticate", 'Bearer realm="practice"')
if status == 405:
self.send_header("Allow", "GET, PUT")
self.end_headers()
self.wfile.write(body)
def error(self, status, code):
self.reply(status, {"error": {"code": code, "message": code.replace("_", " ")}})
def do_GET(self):
self.dispatch()
def do_PUT(self):
self.dispatch()
def do_POST(self):
self.error(405, "method_not_allowed")
def dispatch(self):
if self.headers.get("Authorization") != "Bearer practice-token":
return self.error(401, "authentication_required")
try:
route = urlsplit(self.path)
with closing(sqlite3.connect(database)) as db:
if self.command == "GET" and route.path in ("/v1/products", "/v1/movements"):
params = parse_qs(route.query, strict_parsing=True, keep_blank_values=True)
if set(params) - {"page", "limit"} or any(len(v) != 1 for v in params.values()):
raise ValueError("invalid pagination")
page = int(params.get("page", ["1"])[0])
limit = int(params.get("limit", ["20"])[0])
if not 1 <= page <= 1000000 or not 1 <= limit <= 100:
raise ValueError("invalid pagination")
offset = (page - 1) * limit
if route.path == "/v1/products":
rows = db.execute("SELECT sku, qty FROM products ORDER BY sku LIMIT ? OFFSET ?",
(limit + 1, offset)).fetchall()
items = [{"sku": row[0], "qty": row[1]} for row in rows[:limit]]
else:
rows = db.execute("SELECT id, sku, old_qty, new_qty FROM movements ORDER BY id LIMIT ? OFFSET ?",
(limit + 1, offset)).fetchall()
items = [dict(zip(("id", "sku", "old_qty", "new_qty"), row)) for row in rows[:limit]]
return self.reply(200, {"items": items, "page": page, "limit": limit,
"next_page": page + 1 if len(rows) > limit else None})
if route.query:
raise ValueError("query not supported on this route")
lookup = re.fullmatch(r"/v1/products/([A-Z0-9_-]{1,32})", route.path)
update = re.fullmatch(r"/v1/products/([A-Z0-9_-]{1,32})/quantity", route.path)
if self.command == "GET" and lookup:
sku = lookup.group(1)
row = db.execute("SELECT qty FROM products WHERE sku = ?", (sku,)).fetchone()
if row is None:
return self.error(404, "product_not_found")
return self.reply(200, {"sku": sku, "qty": row[0]})
if self.command == "PUT" and update:
if self.headers.get("Transfer-Encoding") is not None:
raise ValueError("unsupported transfer encoding")
if self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() != "application/json":
return self.error(415, "json_required")
if self.headers.get("Content-Length") is None:
return self.error(411, "content_length_required")
length = int(self.headers["Content-Length"])
if length < 0:
raise ValueError("invalid content length")
if length > 4096:
return self.error(413, "body_limit_exceeded")
self.connection.settimeout(5)
raw = self.rfile.read(length)
if len(raw) != length:
raise ValueError("incomplete body")
data = json.loads(raw.decode("utf-8"))
if not isinstance(data, dict) or set(data) != {"qty"}:
raise ValueError("qty field required")
qty = data["qty"]
if type(qty) is not int or not 0 <= qty <= 1000000:
raise ValueError("invalid qty")
sku = update.group(1)
with db:
row = db.execute("SELECT qty FROM products WHERE sku = ?", (sku,)).fetchone()
if row is None:
return self.error(404, "product_not_found")
if row[0] != qty:
db.execute("UPDATE products SET qty = ? WHERE sku = ?", (qty, sku))
db.execute("INSERT INTO movements(sku, old_qty, new_qty) VALUES (?, ?, ?)",
(sku, row[0], qty))
return self.reply(200, {"sku": sku, "qty": qty})
return self.error(404, "route_not_found")
except (ValueError, UnicodeError):
self.error(400, "invalid_request")
except TimeoutError:
self.error(408, "request_timeout")
except sqlite3.DatabaseError:
self.error(503, "database_unavailable")
return HTTPServer(("127.0.0.1", port), Handler)
if __name__ == "__main__":
server = make_server("practice_inventory.db")
print("Inventory practice server: http://127.0.0.1:8000")
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
Verify the whole request-to-database path
Save this second block as check_inventory_service.py beside the service. It starts an isolated server on an automatically assigned loopback port, performs actual HTTP requests and always shuts down the server. The temporary database keeps the test independent of the manually run practice service. Run it with python check_inventory_service.py; no package installation or external network access is needed.
File: check_inventory_service.py
import json
import threading
from pathlib import Path
from tempfile import TemporaryDirectory
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from inventory_service import make_server
def call(base, path, data=None, token="practice-token"):
body = None if data is None else json.dumps(data).encode("utf-8")
request = Request(base + path, data=body, method="GET" if data is None else "PUT",
headers={"Authorization": "Bearer " + token, "Content-Type": "application/json"})
with urlopen(request, timeout=3) as response:
return response.status, json.load(response)
with TemporaryDirectory() as folder:
server = make_server(Path(folder) / "test.db", port=0)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base = f"http://127.0.0.1:{server.server_port}"
try:
assert call(base, "/v1/products/PEN")[1]["qty"] == 10
assert call(base, "/v1/products/PEN/quantity", {"qty": 7})[1]["qty"] == 7
assert call(base, "/v1/products/PEN/quantity", {"qty": 7})[1]["qty"] == 7
audit = call(base, "/v1/movements")[1]["items"]
assert audit == [{"id": 1, "sku": "PEN", "old_qty": 10, "new_qty": 7}]
for path, data, token, expected in [
("/v1/products/PEN/quantity", {"qty": True}, "practice-token", 400),
("/v1/products/MISSING", None, "practice-token", 404),
("/v1/products/PEN", None, "wrong", 401),
]:
try:
call(base, path, data, token)
except HTTPError as error:
assert error.code == expected
error.close()
else:
raise AssertionError("expected an HTTP error")
assert call(base, "/v1/products/PEN")[1]["qty"] == 7
print("Practice checks passed")
finally:
server.shutdown()
thread.join()
server.server_close()
Expected output
Practice checks passed
Trace an update through five boundaries: HTTP parsing, demo authentication, JSON/schema validation, a transaction containing update plus audit insert, and JSON response serialization. Repeating the same absolute PUT leaves the current quantity unchanged and adds no new audit row. This does not provide a historical request replay contract like Lesson 090; a concurrent later writer can change the current state, and this teaching service uses last-write-wins updates.
Acceptance requires the supplied integration checks plus pagination, invalid media type, oversized body, malformed JSON and a reopen-persistence check. The server is intentionally single-threaded and does not provide a public deployment checklist. Extend it only after documenting concurrency/version checks, real identity and authorization, resource limits, audit retention and backups. Never expose the fabricated token or HTTPServer setup as production security.
Response serialization preview
Python 3.10+. This short preview uses an already validated fixture and serializes a response dictionary. It does not exercise HTTP routing, authentication or database persistence; use the two-file service above for that capstone. Save as lesson100.py or run the preview below.
import json
def response(product_id,stock):
return {'id':product_id,'available':stock>0}
print(json.dumps(response(7,3),sort_keys=True))
Expected output:
{"available": true, "id": 7}
Walkthrough
Trace the integer stock value through the Boolean comparison and JSON serialization. Change stock from 3 to 0 and predict the available field. This helper assumes validated inputs; the full service separately validates requests and persists quantities.
Additional validation example
def validate_page(page):
if isinstance(page,bool) or not isinstance(page,int) or page < 1:
raise ValueError("page must be a positive integer")
return page
assert validate_page(2)==2
print("Page accepted")
Expected: Page accepted. This warmup accepts only positive Python integers and rejects booleans. The full service also bounds the parsed page to one million and the page size to one hundred.
Guided real-world project
Design and implement an inventory API with list, get, update and audit endpoints, validation, database persistence and automated tests.
- Write a requirements specification and sample JSON schema.
- Separate transport, validation, domain logic and persistence layers.
- Implement the simplest successful request/response scenario.
- Handle malformed input, missing resources and authorization failures.
- Test pagination boundaries, timeouts or rate limits where applicable.
- Document setup, security assumptions and rollback procedures.
Acceptance criteria: predictable behavior, no exposed credentials, tests for at least three failure conditions and documented error responses. This project is assigned for implementation; it has not been independently deployed or tested.
Common mistakes and debugging
- Sending credentials through query parameters or printing them in logs.
- Retrying non-idempotent operations without safeguards.
- Ignoring response status, timeouts or malformed JSON.
- Using unchecked URLs from untrusted sources.
- Assuming client-side validation replaces server-side authorization.
Debug by reproducing the request with a safe mock, checking status and headers, inspecting sanitized payloads, and adding regression tests.
Practice with explained answers
Make a prediction before opening each answer. Then trace the example and explain the result in your own words.
Optional hint for question 1
Trace who opens the connection, who commits the transaction, and who closes the resource.
1. Why open a database connection per request?
Each request has clear resource ownership and transaction scope. It also avoids sharing a connection accidentally across execution contexts when the server design later changes.
2. Why does repeating PUT qty=7 create only one audit row?
The first update changes ten to seven. The second sees the same current quantity and makes no state change, so this contract records no additional movement.
3. Is the practice token production authentication?
No. It is a fabricated fixed credential used only on loopback to demonstrate where a check belongs. Real identity, expiry, revocation and object-level permissions are separate requirements.
4. What does the integration test prove that a dictionary serialization test cannot?
It exercises a listening HTTP server, request parsing, authentication, schema validation, SQLite writes, audit behavior and actual response decoding together.
5. Does an absolute PUT prevent lost updates between users?
No. Idempotent assignment and concurrency control are different concerns. This version is last-write-wins; a version field or conditional request policy is needed to reject stale updates.
Mastery checkpoint
Reproduce the sample, explain the protocol implications, complete the project specification, and write at least three meaningful tests. Video and account-synchronized completion are not yet available.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.