How to Implement a REST DELETE Mock Server Returning 204 in Python

A minimal HTTP server mock that responds to DELETE requests with 204, 404, or 403 statuses based on the resource ID.

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_DELETE(self):
        if self.path.startswith("/api/resource/"):
            resource_id = self.path.split("/")[-1]
            if resource_id == "42":
                # Successful delete: 204 No Content
                self.send_response(204)
                self.end_headers()
            elif resource_id == "missing":
                # Resource not found: 404
                self.send_response(404)
                self.end_headers()
            else:
                # Unauthorized: 403
                self.send_response(403)
                self.end_headers()
        else:
            self.send_response(404)
            self.end_headers()

    def log_message(self, format, *args):
        # Suppress default logging for cleaner output
        pass

if __name__ == "__main__":
    server = HTTPServer(("localhost", 8000), MockHandler)
    print("Mock REST server running on http://localhost:8000")
    print("Test DELETE /api/resource/42 -> 204 No Content")
    print("Test DELETE /api/resource/missing -> 404 Not Found")
    print("Test DELETE /api/resource/other -> 403 Forbidden")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.server_close()
        print("\nServer stopped.")

Output

stdout
Mock REST server running on http://localhost:8000
Test DELETE /api/resource/42 -> 204 No Content
Test DELETE /api/resource/missing -> 404 Not Found
Test DELETE /api/resource/other -> 403 Forbidden

How it works

This code uses Python's built-in http.server module to create a lightweight mock API. The do_DELETE method handles DELETE requests and inspects the request path to determine the resource ID. It sends different HTTP status codes (204, 404, 403) based on the resource ID. The log_message override suppresses default server logs for a clean console output. This is a quick way to simulate REST API behavior for testing without external dependencies.

Common mistakes

  • Forgetting to call `self.end_headers()` after `send_response`
  • Not handling the `log_message` method, which clutters the output
  • Using a hardcoded port that might be already in use

Variations

  1. Use Flask or FastAPI for a more production-like mock with routing
  2. Return a JSON body with error details for 404 and 403 responses

Real-world use cases

  • Testing frontend applications against a controlled mock API before the real backend is ready.
  • Simulating delete endpoints in integration tests to verify client error handling and status codes.
  • Providing a lightweight stubbed service for local development when the actual REST API is unavailable.

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.