API design & gRPC
REST best practices, protobuf, API versioning, and backward-compatible service contracts.
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.
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
cont…
Build a Mock REST API with PUT and GET in Python
A minimal mock REST server implementing idempotent PUT for resource replacement and GET for retrieval, built with Python's http.server module.
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from urllib.parse import urlparse
mock_db = {}
class MockAPIHandler(BaseHTTPRequestHandler):
def do_PUT(self):
parsed = urlparse(self.path)
resource_id = parsed.path.strip("/").split("/")[-1]
content_length = int(self.…
How to Build a Batch Operations Multi-Status 207 Mock Server in Python
Build a mock HTTP server that accepts a batch of operations and returns HTTP 207 Multi-Status with per-operation status codes in JSON.
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
class BatchHandler(BaseHTTPRequestHandler):
def do_POST(self):
if self.path != "/batch":
self.send_response(404)
self.end_headers()
return
content_length = int(self.headers.get("Content-Leng…
How to Build a Mock REST GET Endpoint Handler in Python
Create a lightweight mock REST GET server in Python using the standard library, with a dict-based route registry that maps paths to handler functions and returns JSON responses with proper HTTP status codes.
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
# Mock API handler registry
def handle_users():
return {"status": "ok", "data": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}
def handle_products():
return {"status": "ok", "data": [{"id": 101, "name": "Laptop", "price": 999.99}…
How to Build an Idempotency-Key POST Handler in Python
Python HTTP server mock that accepts POST requests and deduplicates them using an Idempotency-Key header, returning the same response for repeated calls.
import hashlib
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
class MockAPI(BaseHTTPRequestHandler):
responses = {}
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length).decode("utf-8")
…
How to Implement Content Negotiation with JSON and XML in Python
Build an HTTP server that returns JSON or XML responses based on the client's Accept header, with a 406 response for unsupported formats.
import json
import xml.etree.ElementTree as ET
from http.server import BaseHTTPRequestHandler, HTTPServer
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
data = {"message": "Hello, world!"}
accept_header = self.headers.get("Accept", "")
if "application/json" in accept_hea…
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.
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 …
How to Mock a Webhook Subscribe Callback URL in Python
Mock a webhook subscribe callback URL using Python's http.server to receive and parse POST requests sent by webhook providers.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
class WebhookHandler(BaseHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers.get('Content-Length', 0))
payload = json.loads(self.rfile.read(content_length)) if content_length else {}
print…
Serve Swagger UI with Python's built-in HTTP server
Hosts a self-contained Swagger UI with a mock OpenAPI spec using only Python's standard library HTTP server.
from http.server import HTTPServer, SimpleHTTPRequestHandler
import os
import tempfile
SWAGGER_HTML = """<!DOCTYPE html>
<html>
<head>
<title>Mock Swagger UI</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@4/swagger-ui.css">
</head>
<body>
<div id="swagger-ui"></div>
<script src…
Version API by Accept Header with Vendor Media Types in Python
Build a mock HTTP server that routes to API versions by parsing vendor-specific Accept headers in Python.
from http.client import HTTPMessage
from http.server import BaseHTTPRequestHandler, HTTPServer
class VendorVersionHandler(BaseHTTPRequestHandler):
def do_GET(self):
accept = self.headers.get("Accept", "")
version = "v1"
if "application/vnd.myapi.v2+json" in accept:
version = "…
Browse by section
Each section groups closely related Python snippets.
API design & gRPC — Python code examples
What you will find here
This page collects api design & grpc snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.