Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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 = "…
How to Mock a Timeout per HTTP Request in Python
Simulate a per-request HTTP timeout using unittest.mock to test timeout handling without network access.
import time
from unittest.mock import Mock, patch
# Simulate an HTTP client that might time out
def fetch_data(url, timeout=5):
time.sleep(0.5) # Simulate network delay
return f"Response from {url}"
# Mock to test timeout behavior without real network
def test_timeout():
mock_response = Mock(side_effect…
How to Build an HTTP Server Request Duration Histogram in Python
Create a small HTTP server that times each GET request, buckets the duration, and prints a histogram on shutdown.
import time
import random
from collections import Counter
from http.server import HTTPServer, BaseHTTPRequestHandler
class HistogramHandler(BaseHTTPRequestHandler):
response_times = Counter()
def do_GET(self):
start = time.perf_counter()
time.sleep(random.uniform(0.001, 0.1))
duratio…
How to Check Uptime with a Synthetic HTTP Mock in Python
Run a mock HTTP server locally and probe it with urllib to measure synthetic uptime and response times, perfect for testing monitoring logic without external dependencies.
import http.server
import threading
import time
import urllib.request
class MockHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health":
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
…
How to Generate and Propagate W3C Trace Context Headers in Python
Generate and propagate W3C traceparent and tracestate headers for distributed tracing in Python, with mock service headers.
import uuid
def generate_w3c_traceparent(trace_id=None, parent_id=None, flags="01"):
if trace_id is None:
trace_id = uuid.uuid4().hex[:32]
if parent_id is None:
parent_id = uuid.uuid4().hex[:16]
return f"00-{trace_id}-{parent_id}-{flags}"
def create_mock_headers(service_name, trace_id=N…
How to Mock HTTP Client Latency in Python
Simulate outbound HTTP request latency with configurable ranges to test timeouts, retries, and SLO monitoring without external services.
import time
import random
def mock_latency(host: str, min_ms: int = 100, max_ms: int = 500) -> dict:
"""Simulate an outbound HTTP request with mock latency."""
latency_ms = random.randint(min_ms, max_ms)
start = time.perf_counter()
time.sleep(latency_ms / 1000)
elapsed_ms = (time.perf_counter() - …
How to Mock an OTLP HTTP Endpoint in Python
This code implements a lightweight HTTP server that accepts OTLP/HTTP trace exports, stores spans by trace ID, and exposes them via a simple GET endpoint for debugging.
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from collections import defaultdict
class TraceHandler(BaseHTTPRequestHandler):
traces = defaultdict(list)
def do_POST(self):
if self.path == "/v1/traces":
length = int(self.headers.get("Content-Length", 0))
…
How to Ship Logs to an Aggregator Endpoint in Python
Ship batched log entries to a mock HTTP aggregator endpoint with proper error handling and response status.
import json
import requests
from datetime import datetime, timezone
LOG_ENTRIES = [
{"timestamp": "2024-01-15T10:00:00Z", "level": "INFO", "message": "Server started"},
{"timestamp": "2024-01-15T10:00:05Z", "level": "WARN", "message": "High memory usage"},
{"timestamp": "2024-01-15T10:00:10Z", "level": "E…
Correlation ID HTTP header mock in Python
A lightweight HTTP server that echoes or generates correlation IDs to help test distributed systems.
import json
import uuid
from http.server import BaseHTTPRequestHandler, HTTPServer
class CorrelationHandler(BaseHTTPRequestHandler):
CORRELATION_HEADER = "X-Correlation-ID"
def do_GET(self):
correlation_id = self.headers.get(self.CORRELATION_HEADER) or str(uuid.uuid4())
response = {
…
How to Build an OAuth Client Credentials Mock Server in Python
A minimal HTTP mock server implementing the OAuth 2.0 client credentials grant for local testing and microservice development.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
TOKENS = {"valid_token": "demo_access_token", "client_id": "my_service"}
class OAuthHandler(BaseHTTPRequestHandler):
def do_POST(self):
if self.path == "/oauth/token":
length = int(self.headers.get("Content-Length", 0))
…
How to Mock Service Versioning URI in Python
Run a minimal HTTP server in Python that routes requests to different versions of a service URI like /v1/users vs /v2/users.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class VersionedHandler(BaseHTTPRequestHandler):
def _send_json(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
…
How to Mock an API Gateway Router in Python
Create a lightweight HTTP server that routes requests to mock microservice responses, simulating an API gateway for local development and testing.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class SimpleGateway(BaseHTTPRequestHandler):
def do_GET(self):
routes = {
"/users": {"service": "user-service", "status": "ok", "count": 42},
"/orders": {"service": "order-service", "status": "ok", "count": 17}…
How to Mock an Ambassador Edge Proxy in Python
Build a lightweight mock Ambassador edge proxy with Python's http.server that responds to health and user endpoint requests for local development and testing.
import http.server
import json
import urllib.parse
import threading
class AmbassadorProxyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
parsed = urllib.parse.urlparse(self.path)
if parsed.path == "/health":
self.send_response(200)
self.send_header("Content-T…
Retry idempotent GET requests in Python
A Python function that retries an idempotent GET request a fixed number of times with a delay between attempts, raising a RuntimeError only after all retries fail.
import time
import urllib.error
import urllib.request
from http.client import HTTPException
def fetch_with_retry(url, max_retries=3, delay=1.0):
for attempt in range(1, max_retries + 1):
try:
with urllib.request.urlopen(url, timeout=5) as response:
return response.read().decode…
ACME LetsEncrypt Mock Challenge Server in Python
A minimal HTTP server that serves key authorizations for ACME/Let's Encrypt DNS-01 or HTTP-01 challenges during testing and validation.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
# In-memory store simulating the ACME challenge token -> key authorization pair
challenge_store = {
"token_example": "token_example.key_authorization"
}
class AcmeChallengeHandler(BaseHTTPRequestHandler):
def do_GET(self):
# Extra…
How to Create Secure Session Cookies in Python with Secure, HttpOnly, and SameSite Flags
This code demonstrates how to create a secure session cookie using Python's stdlib, setting Secure, HttpOnly, and SameSite attributes to protect against common web vulnerabilities.
import http.cookies
import secrets
class SessionManager:
def __init__(self):
self.cookie = http.cookies.SimpleCookie()
def create_session_cookie(self, session_id=None):
session_id = session_id or secrets.token_hex(16)
self.cookie["session"] = session_id
self.cookie["session"][…
How to Enforce a Strict Referrer Policy in Python
Validate HTTP headers to enforce a strict same-origin Referrer policy, accepting only origin-only URLs or absent Referer values.
import re
from unittest.mock import patch
def strict_referrer_policy(headers):
"""Return True if Referer header is absent or strictly same-origin."""
referer = headers.get("Referer")
if referer is None:
return True
# Strict-Origin-When-Cross-Origin allows same-origin full URL
# but here we…
How to Mock HTTP Responses to Verify HSTS Headers in Python
This code demonstrates how to use unittest.mock to intercept and capture HTTP response headers, specifically the Strict-Transport-Security header, from a mocked HTTPServer handler for security validation.
from http.server import BaseHTTPRequestHandler, HTTPServer
from unittest.mock import patch
class StrictTransportMock(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
self.end_headers()
…
How to Mock a Content Security Policy Header in Python
Mock a Content-Security-Policy header locally and verify it's served correctly using Python's built-in HTTP server.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
CSP_HEADER = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"
class MockServer(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/":
self.send_response(200)
self.send_header("…
How to Set a SameSite Cookie in Python
Set a SameSite cookie attribute in Python using the standard library's SimpleCookie class.
from http.cookies import SimpleCookie
def set_same_site_cookie(name, value, same_site="Lax"):
cookie = SimpleCookie()
cookie[name] = value
cookie[name]["path"] = "/"
cookie[name]["samesite"] = same_site
return cookie[name].OutputString()
if __name__ == "__main__":
print(set_same_site_cookie("…
How to Test X-Content-Type-Options nosniff in Python with Mocks
Mock httpx responses and verify that a server's X-Content-Type-Options header includes nosniff to prevent MIME sniffing.
import httpx
from unittest.mock import Mock, patch
def fetch_headers(url: str) -> dict:
response = httpx.get(url)
return dict(response.headers)
def mock_nosniff_check(response) -> bool:
content_type = response.headers.get("content-type", "")
x_content_type_options = response.headers.get("x-content-ty…
OAuth2 authorization code flow mock in Python
A minimal HTTP server that mocks the OAuth2 authorization code flow, issuing codes via /authorize and exchanging them for tokens at /token.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
AUTH_CODE_STORE = {}
CLIENT_ID = "demo-client"
REDIRECT_URI = "http://localhost:8000/callback"
class OAuthHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
…
How to Create a Liveness Probe HTTP Mock in Python
Build a lightweight HTTP server in Python that mimics a Kubernetes-style liveness endpoint, returning JSON health status for local testing.
import http.server
import threading
import time
class LivenessHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/healthz":
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfi…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
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.