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.
Python code
38 linesimport 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
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
- Use `ThreadingHTTPServer` to handle multiple requests concurrently
- 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
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
Keep learning
Related tutorials and quizzes for this topic.