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.

Easy Python 3.9+ Aug 9, 2026 Microservices patterns 14 views 0 copies

Python code

32 lines
Python 3.9+
from 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

stdout
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

  1. Add `do_POST` and `do_PUT` handlers to simulate write operations for other services.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Microservices patterns

Related tutorials and quizzes for this topic.