Build a Bulk Array POST Mock Server in Python
Creates an HTTP mock server that accepts POST requests with a JSON array and returns incremental IDs for each item.
Python code
40 linesimport json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
class MockHandler(BaseHTTPRequestHandler):
def do_POST(self):
if urlparse(self.path).path != "/bulk":
self.send_response(404)
self.end_headers()
return
content_length = int(self.headers["Content-Length"])
request_body = json.loads(self.rfile.read(content_length))
if not isinstance(request_body, list):
self.send_response(400)
self.end_headers()
return
created_records = [
{"id": index + 1, "data": item}
for index, item in enumerate(request_body)
]
response = {"created": created_records, "count": len(created_records)}
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 # Suppress default logging for cleaner output
def run_server():
server = HTTPServer(("localhost", 8080), MockHandler)
print("Mock server running on http://localhost:8080")
server.serve_forever()
if __name__ == "__main__":
run_server()
Output
Mock server running on http://localhost:8080
How it works
The BaseHTTPRequestHandler class provides a lightweight HTTP server foundation without external dependencies. The do_POST method handles incoming POST requests, reads the body using the Content-Length header, and parses it as JSON. A list comprehension assigns sequential IDs starting at 1, mimicking a bulk database insert. The server sends a 201 status with the created records, and suppresses default logging for cleaner output.
Common mistakes
- Returning 200 instead of 201 for successful resource creation
- Not validating that the request body is a JSON array before processing
- Missing Content-Type header on the response, causing clients to guess
- Forgetting to encode the response string to bytes before writing
Variations
- Use Flask or FastAPI to avoid manually parsing headers and request bodies
- Return the full created record including any computed server-side fields
Real-world use cases
- Mocking a bulk insertion API during frontend development before the backend exists.
- Testing client code that sends array payloads against a simulated REST endpoint.
- Stubbing a batch import service in demo environments for financial or inventory data.
Sponsored
More from API design & gRPC
- 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
- How to Add HATEOAS Links to a Python API Response easy
Keep learning
Related tutorials and quizzes for this topic.