How to mock a REST POST endpoint in Python

Create a simple mock REST server that responds to POST requests with a 201 status and a JSON body.

Easy Python 3.9+ Aug 9, 2026 API design & gRPC 12 views 0 copies

Python code

38 lines
Python 3.9+
import json
from http.server import BaseHTTPRequestHandler, HTTPServer


class MockHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(content_length) if content_length else b"{}"
        try:
            data = json.loads(body)
        except json.JSONDecodeError:
            data = {}

        resource_id = data.get("id", 1)
        response = {"id": resource_id, "status": "created"}

        self.send_response(201)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(json.dumps(response).encode())

    def log_message(self, format, *args):
        pass


def run_mock_server(port=8000):
    server = HTTPServer(("localhost", port), MockHandler)
    print(f"Mock server running on port {port}")
    try:
        server.handle_request()
    except KeyboardInterrupt:
        pass
    finally:
        server.server_close()


if __name__ == "__main__":
    run_mock_server()

Output

stdout
Mock server running on port 8000

How it works

The BaseHTTPRequestHandler processes each HTTP method via methods like do_POST. Content-Length tells how many bytes to read from the request body; the code reads that many and parses it as JSON. The handler sends a 201 status with a JSON response mimicking a successful resource creation. handle_request() serves a single request, which is enough for quick tests; log_message is overridden to keep output clean.

Common mistakes

  • Forgetting to read the request body, causing JSON parsing errors
  • Using `send_response(200)` instead of `201 Created` for resource creation
  • Not setting `Content-Type` header to `application/json`
  • Using a loop when only one request is needed, blocking the script

Variations

  1. Use `ThreadingHTTPServer` to handle multiple requests concurrently
  2. Use Flask or FastAPI for more realistic mocking with routing and templates

Real-world use cases

  • Local integration tests for front-end apps that need a fake API endpoint.
  • Stubbing third-party services in CI to avoid real network calls.
  • Prototyping client code before the backend is implemented.

Sponsored

Run this sample

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

Open editor

More from API design & gRPC

Related tutorials and quizzes for this topic.