Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Build a Mock Route53 DNS API in Python
Create a mock DNS API server in Python that simulates Route53 record lookups and updates using the standard library.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
class DNSUpdateHandler(BaseHTTPRequestHandler):
records = {"example.com": "1.2.3.4"}
def do_GET(self):
domain = parse_qs(urlparse(self.path).query).get("domain", [""])[0]
if dom…
How to Create a Mock Docker Registry Auth Token Server in Python
Build a mock Docker Registry token authentication server that issues signed JWT-like tokens for push and pull access using Python's standard library.
import base64
import hashlib
import hmac
import json
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
class TokenAuthHandler(BaseHTTPRequestHandler):
"""Mock Docker Registry token authentication server."""
SECRET_KEY = b"mock-secret-key"
def generate_token(self, username: str, pas…
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 Mock HTTP 304 Responses with If-None-Match in Python
Spin up a local HTTP server that returns a 304 Not Modified when a request carries a matching ETag, useful for testing cache behavior.
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
import urllib.request
ETAG = '"abc123"'
BODY = b'{"status": "ok"}'
class MockServer(BaseHTTPRequestHandler):
def do_GET(self):
if self.headers.get('If-None-Match') == ETAG:
self.send_response(304)
…
How to Mock a 202 Accepted Long-Running Operation in Python
Build a mock HTTP server that returns a 202 Accepted response immediately and simulates a long-running operation in the background with threading.
import time
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
class MockHandler(BaseHTTPRequestHandler):
def do_POST(self):
if self.path == "/long-running":
self.send_response(202)
self.send_header("Content-Type", "application/json")
self.end_h…
How to Mock a Chunked Encoding Streaming Response in Python
Build a local mock HTTP server with Python's http.server that streams a chunked-encoded response with a 0.5s delay per chunk.
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import time
class ChunkedHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Transfer-Encoding", "c…
How to Mock an API Key Header Authentication Server in Python
A minimal HTTP server that validates requests using an X-API-Key header and returns JSON responses for authenticated and unauthenticated calls.
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
API_KEYS = {"test-user": "secret-key-123"}
class AuthHandler(BaseHTTPRequestHandler):
def do_GET(self):
auth = self.headers.get("X-API-Key")
if not auth or auth not in API_KEYS.values():
self.send_response…
How to Stop Receiving Requests Until Ready in Python
A mock server that refuses requests until a readiness gate is passed, simulating fail-stop behavior for production reliability.
import random
import time
class MockServer:
def __init__(self):
self.ready = False
self.requests_received = 0
def readiness_check(self):
"""Simulates a readiness probe. Returns True only when ready."""
if not self.ready:
return False
return True
def r…
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 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 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("…
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.