API design & gRPC
REST best practices, protobuf, API versioning, and backward-compatible service contracts.
Convert Protobuf to JSON and Dict in Python
Provides static helper methods to convert between protobuf messages, JSON strings, and Python dictionaries using the google.protobuf library.
from google.protobuf.json_format import MessageToJson, Parse
import json
class DataConverter:
"""Helper class to convert between protobuf messages and common formats."""
@staticmethod
def to_json(message, indent=2):
"""Convert a protobuf message to JSON string."""
return MessageToJson(me…
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 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 Poll an Operation Status Endpoint in Python
Mock a polling endpoint in Python that simulates checking an async operation's status until it completes or times out.
import time
import random
def poll_status(url: str, timeout: float = 5.0) -> dict:
"""Mock a polling endpoint that eventually returns a completed status."""
start = time.time()
while time.time() - start < timeout:
# Simulate delayed response
time.sleep(0.2)
# 80% chance to report …
How to mock a REST POST endpoint in Python
Create a simple mock REST server that responds to POST requests with a 201 status and a JSON body.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
class MockHandler(BaseHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(content_length) if content_length else b"{}"
try:
data = json…
Return Proper HTTP Status Codes Table in Python
Mock HTTP status code table with proper numeric and textual representations, including formatted status lines and a filtered table view.
# Mock HTTP status code table with proper numeric and textual representations
codes = {
200: "OK",
201: "Created",
204: "No Content",
301: "Moved Permanently",
302: "Found",
304: "Not Modified",
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
50…
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.