REST API Architecture & Endpoint Design Studio
Master RESTful microservice architectures, HTTP methods (GET, POST, PUT, DELETE), JSON request payloads, error validation, and status code response standards.
Beginner Tutorials: Relational Databases & RESTful APIs
Master data persistence with SQLite database tutorials and build scalable architectures with REST API standards. Includes interactive Python code sandboxes, flowcharts, unit testing suites, and complete installation guides for Windows, Mac, and Linux.
SQLite Database Tutorials
Select any tutorial script below to inspect its Python source code:
"""
SQLite Connection Demonstration Module.
This script demonstrates connecting to an SQLite database, initializing a cursor,
and safely closing the database connection.
Note: Do NOT name python files 'sqlite3.py' to prevent shadowing the standard library module.
"""
import sqlite3
from typing import Optional
def connect_database(db_name: str = "mydatabase.db") -> Optional[sqlite3.Connection]:
"""Connect to SQLite database file.
Args:
db_name (str): Database file path or name.
Returns:
Optional[sqlite3.Connection]: SQLite connection object if successful.
"""
try:
# Establish connection to the database
connection = sqlite3.connect(db_name)
# Initialize cursor for executing queries
cursor = connection.cursor()
print(f"Successfully connected to database '{db_name}'.")
# Close database connection
connection.close()
print("Database connection closed successfully.")
return connection
except sqlite3.Error as error:
print(f"Error connecting to database: {error}")
return None
def create_connection(db_name: str = "mydatabase.db"):
"""Create and return an active SQLite connection and cursor.
Args:
db_name (str): Database file path or name.
Returns:
Tuple[sqlite3.Connection, sqlite3.Cursor]: Active connection and cursor tuple.
"""
connection = sqlite3.connect(db_name)
cursor = connection.cursor()
return connection, cursor
def close_connection(connection: sqlite3.Connection) -> None:
"""Safely close active SQLite connection."""
if connection:
connection.close()
if __name__ == "__main__":
connect_database()
โก Interactive SQLite Query Sandbox
Select a preset scenario below or type custom Python database code:
Car database initialized and populated with 8 static records. Schema: Car (Name TEXT, Model TEXT, Version REAL, Description TEXT)
๐งช SQLite & Security Unit Tests (`tests/test_sqlite_modules.py`)
Complete test suite validating table creation, query parameterization, CRUD logic, and SQL injection prevention:
import unittest
import sqlite3
from cloud_app.tutorials.sqlite_db import setup_database, read_filtered_records, read_by_user_input
class TestSQLiteDatabaseModules(unittest.TestCase):
def setUp(self):
self.db_path = ":memory:"
self.conn = setup_database(self.db_path)
def test_database_initialization(self):
cur = self.conn.cursor()
cur.execute("SELECT COUNT(*) FROM Car")
count = cur.fetchone()[0]
self.assertEqual(count, 8)
def test_sql_injection_prevention(self):
\"\"\"Test tautology attack payload `' OR '1'='1` is safely neutralized.\"\"\"
malicious_name = "' OR '1'='1"
results = read_by_user_input(malicious_name, db_path=self.db_path)
self.assertEqual(len(results), 0) # Parameterized query blocks injection!
๐ฅ๏ธ Pytest Suite Execution Output
๐ Relational Architecture & Query Flowcharts
Step-by-step visual execution flowcharts for database lifecycle management, schema architecture, and parameterized security:
๐ 1. Relational Database Schema & Application Architecture Diagram
High-level architectural interaction between Python Web Backend, SQL Execution Pipeline, and SQLite Relational Storage:
๐ 2. Database Connection Lifecycle Flowchart
Visual execution sequence for opening connection, initializing cursor, executing statements, committing transactions, and closing resources:
sqlite3.connect()
conn.cursor()
cur.execute(sql, params)
conn.commit() / fetchall()
conn.close()
๐ก๏ธ 3. Parameterized Query SQL Injection Defense Flowchart
How placeholder parameter binding (?) neutralizes malicious injection payloads like ' OR '1'='1:
"' OR '1'='1"
("SELECT ... ?", (input,))
Literal Data Value
0 Rows Returned
๐ Setup & Installation Guide (Win/Mac/Linux)
๐ช Windows Setup
- SQLite is built into Python's Standard Library (no external install needed!).
- Install DB Browser for SQLite: Download installer from
sqlitebrowser.org.
๐ macOS Setup
- SQLite is pre-installed on macOS.
- Install DB Browser via Homebrew:
brew install --cask db-browser-for-sqlite
๐ง Linux (Ubuntu / Debian)
- Install SQLite CLI & GUI:
sudo apt update && sudo apt install sqlite3 sqlitebrowser
REST API Microservice Controller
In-memory REST API controller implementing standard GET, POST, PUT, and DELETE HTTP endpoints (`cloud_app/tutorials/rest_basics.py`):
import json
from typing import Dict, Any, Tuple
class RESTStudioRunner:
"""In-memory REST API service controller."""
def __init__(self):
self.services = {
1: {"id": 1, "name": "PostgreSQL Database Service", "category": "Database", "status": "active"},
2: {"id": 2, "name": "Redis Cache Cluster", "category": "Caching", "status": "active"},
3: {"id": 3, "name": "RabbitMQ Message Queue", "category": "Messaging", "status": "idle"}
}
def handle_request(self, method: str, path: str, payload: Dict[str, Any] = None) -> Tuple[int, Dict[str, Any]]:
"""Route HTTP method and path to handler."""
if method == "GET" and path == "/api/v1/services":
return 200, {"status_code": 200, "message": "OK", "count": len(self.services), "data": list(self.services.values())}
elif method == "GET" and path.startswith("/api/v1/services/"):
try:
service_id = int(path.split("/")[-1])
service = self.services.get(service_id)
if service:
return 200, {"status_code": 200, "data": service}
return 404, {"status_code": 404, "error": f"Service #{service_id} Not Found"}
except ValueError:
return 400, {"status_code": 400, "error": "Invalid Service ID"}
elif method == "POST" and path == "/api/v1/services":
if not payload or "name" not in payload:
return 400, {"status_code": 400, "error": "Field 'name' is required"}
new_id = max(self.services.keys(), default=0) + 1
new_service = {
"id": new_id,
"name": payload["name"],
"category": payload.get("category", "General"),
"status": "active",
}
self.services[new_id] = new_service
return 201, {
"status_code": 201,
"message": "Resource Created Successfully",
"data": new_service,
}
elif method == "PUT" and path.startswith("/api/v1/services/"):
service_id = int(path.split("/")[-1])
if service_id not in self.services:
return 404, {"status_code": 404, "error": f"Service #{service_id} Not Found"}
if payload:
self.services[service_id].update(payload)
return 200, {
"status_code": 200,
"message": "Resource Updated Successfully",
"data": self.services[service_id],
}
elif method == "DELETE" and path.startswith("/api/v1/services/"):
service_id = int(path.split("/")[-1])
if service_id in self.services:
deleted = self.services.pop(service_id)
return 200, {
"status_code": 200,
"message": "Resource Deleted Successfully",
"deleted_id": service_id,
"deleted_name": deleted["name"],
}
return 404, {"status_code": 404, "error": f"Service #{service_id} Not Found"}
return 400, {"status_code": 400, "error": f"Unsupported HTTP Method '{method}'"}
โก Interactive REST Client & Microservice Tester
Select a preset HTTP request or craft custom API client calls:
HTTP Status Code: 200
JSON Response: {'status_code': 200, 'message': 'OK', 'count': 3, 'data': [{'id': 1, 'name': 'PostgreSQL Database Service', 'category': 'Database', 'status': 'active'}, {'id': 2, 'name': 'Redis Cache Cluster', 'category': 'Caching', 'status': 'active'}, {'id': 3, 'name': 'RabbitMQ Message Queue', 'category': 'Messaging', 'status': 'idle'}]}
๐งช REST API Unit Test Suite (`tests/test_rest_tutorial.py`)
import unittest
from cloud_app.tutorials.rest_basics import RESTStudioRunner
class TestRESTTutorial(unittest.TestCase):
def test_post_create_resource(self):
runner = RESTStudioRunner()
status, resp = runner.handle_request("POST", "/api/v1/services", {"name": "Kafka"})
self.assertEqual(status, 201)
๐ REST Standards & Client Tooling Guide
๐ HTTP Verbs & Conventions
- GET: Retrieve resource representations (Idempotent).
- POST: Create new resources (Returns 201 Created).
- PUT: Replace/Update existing resources.
- DELETE: Remove resources permanently.
๐ง Linux (Ubuntu / Debian)
- Ubuntu/Debian:
sudo apt update && sudo apt install curl httpie - Postman via Snap:
sudo snap install postman