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.
Python code
38 linesimport 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
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
- Use Flask or FastAPI for a more production-like mock with routing
- 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
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.