Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

16 matches
Automation & scripting medium

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.

mock-server dns http-server
Python
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…
13 0 Open
Automation & scripting medium

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.

docker registry jwt
Python
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…
16 0 Open
Git + Python medium

How to Build a Branch Protection Audit Mock API in Python

A mock HTTP API that serves branch protection rules for repositories and audits them for compliance, built with Python's standard library.

git api http-server
Python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs

REPOSITORIES = {
    "alpha": {
        "default_branch": "main",
        "branches": ["main", "develop", "feature-x"],
        "protection_rules": {
            "main": {"required_reviews": 2, "dismiss_…
9 0 Open
System design patterns medium

Build a BFF (Backend for Frontend) Mock Aggregator in Python

A minimal HTTP server implementing the BFF pattern that aggregates user data and orders from two mock backends into a single JSON response.

bff http-server aggregation
Python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse


class MockBackendA:
    def get_user(self, user_id):
        return {"id": user_id, "name": "Alice", "service": "backend-a"}


class MockBackendB:
    def get_orders(self, user_id):
        return [
            {…
17 0 Open
API design & gRPC medium

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.

http-server mock-api rest
Python
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…
15 0 Open
API design & gRPC medium

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.

rest-api http-server mock
Python
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.…
15 0 Open
API design & gRPC medium

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.

http-server batch multi-status
Python
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…
13 0 Open
API design & gRPC medium

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.

mock-server rest-api http
Python
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}…
14 0 Open
API design & gRPC medium

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.

http-server idempotency api-mock
Python
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")
…
14 0 Open
API design & gRPC medium

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.

http-server content-negotiation json
Python
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…
11 0 Open
API design & gRPC medium

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.

webhook http-server mock
Python
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…
15 0 Open
API design & gRPC medium

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.

api-versioning accept-header http-server
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 = "…
13 0 Open
Observability & SRE medium

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.

uptime http-server monitoring
Python
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()
   …
14 0 Open
Microservices patterns medium

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.

oauth mock-server microservices
Python
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))
  …
14 0 Open
Auth & security at scale medium

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.

acme letsencrypt http-server
Python
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…
15 0 Open
Auth & security at scale medium

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.

oauth2 http-server mock-server
Python
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)
    …
14 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.