Learning Guide: Local API Mock Server
http.server module : Python's built-in HTTP server framework
BaseHTTPRequestHandler : Base class for handling HTTP requests
HTTPServer : Creates a socket server that listens for HTTP requests
2. Threading and Concurrency
Thread Safety : Using locks to protect shared data (config, logs)
Concurrent Requests : Server handles multiple requests using threading
Race Conditions : Why we need threading.Lock() for shared state
Latency Simulation : time.sleep() to simulate slow networks
Failure Injection : Random failures to test error handling
Flaky Services : Testing retry logic and circuit breakers
Configuration as Code : JSON-based endpoint definitions
Hot Reload : Update config without restarting server
Special Endpoints : __reload, __logs for server management
Add a new endpoint to config.json
Create a template variable for {{date}} (just the date, not time)
Add request body logging
Implement request body validation
Add support for custom response headers per endpoint
Create a CLI command to generate config from OpenAPI spec
Implement the full record-and-replay proxy
Add WebSocket support
Create a web UI for managing endpoints
Add authentication simulation (JWT tokens)
mock_server.py: Main server implementation
config.json: Endpoint configuration
recorder.py: Traffic recording (stretch goal)
test_server.py: Integration tests
Adding a New Template Variable
# In TemplateEngine._render_string()
template = re .sub (
r'\{\{your_variable\}\}' ,
'your_value' ,
template
)
# In MockRequestHandler
def do_PATCH (self ):
self ._handle_request ('PATCH' )
Configuring Endpoint Behavior
{
"path" : " /api/endpoint" ,
"method" : " GET" ,
"response" : {"data" : " value" },
"status" : 200 ,
"latency_ms" : 100 ,
"failure_rate" : 0.1
}
Limitations and Trade-offs
Single Process : Not suitable for high-load testing
No State : Each request is independent (no session management)
Simple Templates : Not a full template engine like Jinja2
No Request Matching : Only exact path matches (no wildcards)
Add request/response middleware
Support for GraphQL endpoints
Rate limiting simulation
Response caching
Metrics and monitoring dashboard
Docker container for easy deployment