How to Mock an API Gateway Router in Python
Create a lightweight HTTP server that routes requests to mock microservice responses, simulating an API gateway for local development and testing.
Python code
32 linesfrom http.server import HTTPServer, BaseHTTPRequestHandler
import json
class SimpleGateway(BaseHTTPRequestHandler):
def do_GET(self):
routes = {
"/users": {"service": "user-service", "status": "ok", "count": 42},
"/orders": {"service": "order-service", "status": "ok", "count": 17},
"/inventory": {"service": "inventory-service", "status": "ok", "count": 130},
}
if self.path in routes:
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(routes[self.path]).encode())
else:
self.send_response(404)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({"error": "route not found"}).encode())
def run_server(port=8080):
server = HTTPServer(("localhost", port), SimpleGateway)
print(f"API gateway mock listening on http://localhost:{port}")
server.serve_forever()
if __name__ == "__main__":
run_server()
Output
API gateway mock listening on http://localhost:8080
GET http://localhost:8080/users → 200 {"service": "user-service", "status": "ok", "count": 42}
GET http://localhost:8080/orders → 200 {"service": "order-service", "status": "ok", "count": 17}
GET http://localhost:8080/inventory → 200 {"service": "inventory-service", "status": "ok", "count": 130}
GET http://localhost:8080/unknown → 404 {"error": "route not found"}
How it works
The HTTPServer from http.server creates a basic web server, while BaseHTTPRequestHandler lets you define custom HTTP methods like do_GET. The routes dictionary maps URL paths to mock service payloads, acting as a routing table. When a request matches, the gateway returns a JSON response with a 200 status; otherwise, it returns a 404 error. This pattern simulates edge routing logic without needing real microservices, making it useful for frontend development or integration testing. Using the standard library keeps dependencies zero and setup minimal.
Common mistakes
- Forgetting to send `end_headers()` before writing the body, causing connection errors.
- Not encoding JSON strings to bytes before writing with `wfile.write()`.
- Assuming the server handles POST or other methods — only GET is implemented here.
Variations
- Add `do_POST` and `do_PUT` handlers to simulate write operations for other services.
- Use `pathlib.Path` to load route definitions from a JSON file for dynamic routing.
Real-world use cases
- Stubbing backend services for frontend development when the real microservices are unavailable.
- Simulating an API gateway in CI/CD tests to validate client request/response handling.
- Providing a local mock for integration tests across multiple services without deploying containers.
Sponsored
More from Microservices patterns
- BFF aggregation pattern: combine multiple service responses in Python easy
- Backward Compatible Schema Evolution in Python medium
- Bulkhead Thread Pool per Service Mock in Python medium
- CQRS with Separate Read and Write Repositories in Python medium
- Cache-Aside Pattern in Python: Per-Service Mock easy
- Consumer Driven Contract Pact Mock in Python medium
Keep learning
Related tutorials and quizzes for this topic.