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…
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 ETag Optimistic Concurrency in Python
Build a lightweight in-memory resource store that uses MD5 hash ETags to prevent lost updates via optimistic concurrency control.
import hashlib
import json
class ResourceStore:
def __init__(self):
self.data = {}
self.etags = {}
def get(self, resource_id):
if resource_id not in self.data:
return None, None
return self.data[resource_id], self.etags[resource_id]
def put(self, resource_id, …
How to Mock Content-Disposition and Extract Filename in Python
Parse and mock Content-Disposition headers in Python to extract filenames, handling both plain and RFC 5987 encoded values.
import os
from pathlib import Path
import re
from unittest.mock import patch
def get_filename_from_content_disposition(header_value):
"""
Extract filename from a Content-Disposition header value.
Supports both filename and filename* parameters (RFC 5987).
"""
if not header_value:
return No…
How to Mock a GraphQL Query Type in Python
Create a lightweight mock of a GraphQL Query type to simulate repository lookups without a server.
import json
class Query:
def __init__(self):
self.starred_repos = [
{"id": 1, "name": "graphql", "owner": "graphql"}
]
def repository(self, name):
if name == "graphql":
return {"id": 1, "name": "graphql", "stargazerCount": 85000}
return None
if __name…
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…
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…
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…
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.