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.

Medium Python 3.9+ Aug 9, 2026 API design & gRPC 15 views 0 copies

Python code

40 lines
Python 3.9+
import 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

stdout
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

  1. Use Flask or FastAPI to avoid manually parsing headers and request bodies
  2. 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

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.