Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

38 matches
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 easy

How to Implement a PATCH Partial Update Merge Dict in Python

Implements a recursive merge function that applies HTTP PATCH-like partial updates to a nested dictionary while preserving untouched fields.

http rest dict-merge
Python
import json

def patch_merge(target: dict, patch: dict) -> dict:
    """Simulate HTTP PATCH semantic: shallow-merge patch into a copy of target."""
    merged = target.copy()
    for key, value in patch.items():
        if isinstance(value, dict) and isinstance(merged.get(key), dict):
            merged[key] = patch_m…
13 0 Open
API design & gRPC easy

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.

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

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.

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

Implement If-Match Precondition Update in Python

A mock resource store that uses the If-Match header's ETag to guard updates, preventing overwrites from stale clients.

api etag optimistic-concurrency
Python
from dataclasses import dataclass
from typing import Optional


@dataclass
class Resource:
    id: str
    version: int = 1
    data: str = ""
    etag: str = "etag-1"


class MockResourceStore:
    def __init__(self):
        self.resources = {}

    def update(self, resource_id: str, new_data: str, if_match: Optiona…
13 0 Open
Reliability & rate limiting medium

How to Mock a Liveness Check and Restart a Process in Python

Simulate a failing process and restart it after a liveness check fails, using a mock class and a liveness loop.

liveness restart mock
Python
import subprocess
import sys
import time
import os

class ProcessMock:
    def __init__(self, name, fail_after_seconds=3):
        self.name = name
        self.fail_after = fail_after_seconds
        self.start_time = None
        self.is_running = False

    def start(self):
        self.start_time = time.time()
   …
14 0 Open
Observability & SRE easy

How to Mock Service Resource Attributes in Python

Temporarily override service name, version, and other resource attributes with a context manager, then restore them automatically.

context-manager observability testing
Python
from contextlib import contextmanager
import random

_SERVICE_ATTRIBUTES = {
    "service.name": "payment-api",
    "service.version": "1.4.2",
    "service.instance.id": str(random.randint(10000, 99999)),
    "service.namespace": "production",
}

@contextmanager
def mock_service_attributes(**overrides):
    """Tempor…
14 0 Open
Big data & Spark easy

How to Truncate Lineage Back to a Checkpoint in Python

Walks a linked list of lineage nodes upward to find the nearest checkpoint and returns that node, truncating the lineage.

lineage checkpoint linked-list
Python
class LineageNode:
    def __init__(self, name, parent=None, checkpoint=None):
        self.name = name
        self.parent = parent
        self.checkpoint = checkpoint

    def truncate_at_checkpoint(self):
        """Truncate lineage back to the last checkpoint."""
        current = self
        while current.check…
16 0 Open
ML engineering pipelines easy

Build a Mock Random Forest Classifier in Python

Create a simple random-forest-like classifier with random majority voting between trees, including fit, predict, and predict_proba methods.

random forest mock machine learning
Python
import random


class MockRandomForest:
    def __init__(self, n_trees=10, random_state=42):
        self.n_trees = n_trees
        self.random_state = random_state
        self.classes_ = None
        self._class_counts = None
        random.seed(random_state)

    def fit(self, X, y):
        self.classes_ = sorted(…
13 0 Open
ML engineering pipelines easy

How to Build a Mock Offline Feature Store in Python

Build an in-memory mock of an offline feature store with a dict-based FeatureStore class for storing and retrieving ML features by entity ID.

feature-store ml-pipeline mock
Python
from datetime import datetime
from collections import defaultdict


class FeatureStore:
    """Simple in-memory mock of an offline feature store."""

    def __init__(self):
        self._features = defaultdict(dict)

    def ingest(self, entity_id, feature_name, value, timestamp=None):
        ts = timestamp or datet…
14 0 Open
Auth & security at scale medium

How to Mock Environment Variables in Python

A context manager that injects and restores environment variables for isolated testing of config-dependent code.

env vars context manager testing
Python
import os

class EnvInjector:
    def __init__(self, mock_vars=None):
        self.mock_vars = mock_vars or {}
        self.original = {}

    def __enter__(self):
        for key, value in self.mock_vars.items():
            if key in os.environ:
                self.original[key] = os.environ[key]
            os.env…
14 0 Open
Production deployment patterns easy

How to Mock time.sleep in a Python PreStop Hook

This code simulates a Kubernetes PreStop hook that delays shutdown, then mocks time.sleep to verify the hook logic without real delay.

mocking prestop kubernetes
Python
import subprocess
import sys
import time
from unittest.mock import patch

def pre_stop_hook():
    """Simulate a Kubernetes PreStop hook that sleeps before shutdown."""
    print("PreStop hook started: delaying shutdown")
    time.sleep(3)
    print("PreStop hook completed: ready to shutdown")

if __name__ == "__main_…
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.