Reference library

Python Code Samples

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

141 matches
Automation & scripting medium

How to Track GitHub Stars, Forks, and Watchers in Python

Automatically fetch and track stars, forks, and watchers for multiple GitHub repositories, saving snapshots locally as JSON files for historical analysis.

github api automation
Python
import os
import time
import json
import requests
from pathlib import Path
from datetime import datetime

REPOS = [
    "psf/requests",
    "python/cpython",
    "pallets/flask",
]
DATA_DIR = Path("github_metrics")

def fetch_repo_stats(repo):
    url = f"https://api.github.com/repos/{repo}"
    resp = requests.get(ur…
39 0 Open
Automation & scripting easy

Monitor Website Uptime with Python

Periodically check if a website is reachable and its HTTP status is 200, logging the status with timestamps.

monitoring uptime requests
Python
import requests
import time

def check_website(url):
    try:
        response = requests.get(url, timeout=5)
        if response.status_code == 200:
            return True
        else:
            return False
    except requests.ConnectionError:
        return False
    except requests.Timeout:
        return Fals…
38 0 Open
Automation & scripting easy

Rotate API keys in Python by updating an .env template

Replace an old API key with a new one inside an .env template file, with a guard for missing keys.

api-keys env-files automation
Python
import json
from pathlib import Path

def rotate_api_keys(env_template_path: Path, old_key: str, new_key: str) -> None:
    """Replace an old API key with a new one in an .env template file."""
    content = env_template_path.read_text()
    if old_key not in content:
        print(f"Error: '{old_key}' not found in {e…
13 0 Open
Automation & scripting medium

Scrape HTML Tables in Python with html.parser

Extract data from HTML tables using Python's built-in html.parser module, without third-party dependencies, by overriding callback methods to track table, row, and cell states.

html scraping parser
Python
import html.parser
from urllib.request import urlopen


class TableParser(html.parser.HTMLParser):
    def __init__(self):
        super().__init__()
        self.in_table = False
        self.in_row = False
        self.in_cell = False
        self.current_cell = []
        self.rows = []
        self.row = []

    d…
12 0 Open
Data pipelines & processing medium

Extract Schema.org Structured Data from Any Website in Python

A Python tool that fetches a webpage and extracts all JSON-LD structured data (Schema.org) embedded in <script> tags with type="application/ld+json".

web-scraping structured-data schema-org
Python
import requests
from bs4 import BeautifulSoup
import json

def extract_schema_org(url):
    """Extract structured data (Schema.org) from a website."""
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        return {"err…
48 0 Open
Data pipelines & processing easy

Fan Out Records to Multiple Sinks in Python

Distribute the same records across multiple target sinks (database, API, queue, etc.) using a defaultdict-based fan-out pattern.

fan-out defaultdict records
Python
import json
from collections import defaultdict

SINKS = ["database", "api", "message_queue", "data_lake", "monitoring"]

def fan_out(records, *sinks):
    dist = defaultdict(list)
    for record in records:
        for sink in sinks:
            dist[sink].append(record)
    return dict(dist)

if __name__ == "__main_…
12 0 Open
Git + Python easy

Create a Mock GitHub Release API in Python for Testing gh CLI

Build an in-memory GitHub Releases API mock that mimics create_release and list_releases for unit testing gh CLI stubs without network calls.

mock-api github testing
Python
import json
from unittest.mock import patch, Mock

class GitHubReleaseAPI:
    """Mock GitHub Releases API for testing gh CLI stub behavior."""
    
    def __init__(self):
        self.releases = {}
        self.counter = 1
    
    def create_release(self, repo, tag, name=None, notes=None):
        release_id = self…
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
Git + Python medium

Python Script to Rotate a Leaked API Key

A checklist-driven Python script that scans a codebase for a leaked API key, replaces it with a new one, and prints a step-by-step rotation checklist.

security secrets file-scanning
Python
#!/usr/bin/env python3
"""Checklist for rotating a leaked API key across a codebase."""

import re
from pathlib import Path


CHECKLIST = [
    "Identify all files containing the leaked key",
    "Generate a new key with sufficient entropy",
    "Update the secret storage/CI environment variables",
    "Replace the ol…
14 0 Open
Cloud + Python medium

Build a URL Shortener Client with Python

A Python class that shortens long URLs and resolves short codes using a REST API built with requests.

url shortener api
Python
import json
import sys
import requests

class URLShortenerClient:
    def __init__(self, base_url="http://tinyurl.com"):
        self.base_url = base_url

    def shorten_url(self, long_url):
        payload = {"url": long_url}
        headers = {"Content-Type": "application/json"}
        response = requests.post(f"{…
55 0 Open
Cloud + Python medium

Exponential Backoff with Jitter for Cloud API Calls in Python

A Python snippet demonstrating exponential backoff with jitter for retrying transient cloud API failures, using a simulated client that has a configurable success rate.

retry backoff jitter
Python
import random
import time


def exponential_backoff_with_jitter(retries=5, base_delay=0.5, max_delay=4.0, jitter_factor=0.3):
    for attempt in range(1, retries + 1):
        delay = min(max_delay, base_delay * (2 ** (attempt - 1)))
        jitter = delay * random.uniform(-jitter_factor, jitter_factor)
        effect…
18 0 Open
Cloud + Python easy

Generate an Idempotency-Key header mock with UUID in Python

This code provides a mock idempotency service that generates a UUID-based Idempotency-Key header token and validates it, useful for simulating production API behavior in tests.

uuid idempotency mock
Python
import uuid

class MockIdempotencyService:
    def __init__(self):
        self._tokens = {}

    def get_token(self, header_name="Idempotency-Key"):
        token = str(uuid.uuid4())
        self._tokens[header_name] = token
        return token

    def validate(self, header_name="Idempotency-Key"):
        return s…
11 0 Open
Cloud + Python easy

How to Implement Retry with Exponential Backoff for Cloud API 429 Errors in Python

Implement a retry-with-backoff loop in Python to handle 429 throttling errors from cloud APIs, using exponential delay between attempts.

retry backoff 429
Python
import time
import random
import requests


def api_call(attempt):
    """Mock cloud API that returns 429 for the first two attempts."""
    if attempt < 2:
        return 429, "Too Many Requests"
    return 200, {"data": "success"}


def retry_with_backoff(api_func, max_retries=3, base_delay=0.1):
    for attempt in …
12 0 Open
Cloud + Python easy

How to Mock AWS Secrets Manager in Python

Create a lightweight mock of AWS Secrets Manager's get_secret_value API to test secret retrieval without cloud dependencies.

aws secrets-manager mock
Python
import json
from typing import Optional


class MockSecretsManager:
    """A simple mock of AWS Secrets Manager's get_secret_value API."""

    def __init__(self):
        self._secrets: dict[str, str] = {}

    def create_secret(self, secret_id: str, secret_value: str) -> None:
        """Store a secret value under a…
14 0 Open
Cloud + Python easy

How to Mock Azure Service Bus Queue in Python

A lightweight in-memory mock of the Azure Service Bus queue API for local testing without cloud dependencies.

azure service-bus mock
Python
import json
import time
from collections import deque

class ServiceBusQueueMock:
    def __init__(self, queue_name):
        self.queue_name = queue_name
        self._messages = deque()
        self._dead_letter_queue = deque()
        self._message_counter = 0

    def send_message(self, body, message_id=None, prop…
14 0 Open
Cloud + Python easy

How to Paginate a List with a Generator in Python

Define a generator that yields list items in fixed-size pages, simulating pagination for cloud resource APIs.

generator pagination cloud
Python
from typing import List, Iterator

def paginate_generator(items: List[str], page_size: int = 3) -> Iterator[List[str]]:
    """Yield items in fixed-size chunks with a mock pagination pattern."""
    for i in range(0, len(items), page_size):
        yield items[i:i + page_size]

if __name__ == "__main__":
    resources…
11 0 Open
Cloud + Python easy

How to Parse Cloud JSON Data in Python

A helper function that safely parses JSON payloads from cloud services into a clean dict with defaults and error handling.

json cloud parsing
Python
import json
from typing import Dict, Any

def parse_cloud_data(payload: str) -> Dict[str, Any]:
    """Parse a JSON payload from a cloud service into a clean dict."""
    try:
        data = json.loads(payload)
        return {
            "status": data.get("status", "unknown"),
            "region": data.get("region…
15 0 Open
Cloud + Python easy

How to Parse an AWS API Gateway Proxy Event in Python

Extract and parse common fields from a mock API Gateway proxy event, turning the JSON body into a native Python dict.

aws lambda api-gateway
Python
import json
from typing import Any, Dict, Optional


def parse_proxy_event(event: Dict[str, Any]) -> Dict[str, Any]:
    """Extract and parse common fields from an API Gateway proxy event."""
    body = event.get("body", "")
    if isinstance(body, str):
        body = json.loads(body) if body else {}
    elif body is…
13 0 Open
Cloud + Python medium

Mock Route53 change_resource_record_sets in Python

This code demonstrates how to mock AWS Route53 change_resource_record_sets API calls using the botocore Stubber, allowing you to test DNS update logic without touching real infrastructure.

aws route53 boto3
Python
import boto3
from botocore.exceptions import ClientError

def mock_change_resource_record_sets():
    """Demonstrates Route53 change_resource_record_sets with a mock client."""
    # Create a mock Route53 client
    route53 = boto3.client('route53', region_name='us-east-1', 
                          aws_access_key_id…
14 0 Open
Cloud + Python easy

Mock SSM Parameter Store Get Parameters by Path in Python

This code implements a simple mock of the AWS SSM Parameter Store get_parameters_by_path API, returning parameters under a given path with recursive and non-recursive options.

aws ssm parameter-store
Python
import json

class MockSSM:
    def __init__(self, parameters):
        self.parameters = parameters

    def get_parameters_by_path(self, path, recursive=True):
        result = []
        for key, value in self.parameters.items():
            if recursive:
                if key.startswith(path):
                   …
16 0 Open
Modern tooling easy

How to Create a Rich Console Progress Bar Mock in Python

This code uses Rich's Console and Progress API to build a simulated progress bar for a long-running task, updating progress and printing status messages.

rich progress-bar cli
Python
import time
from rich.console import Console
from rich.progress import Progress, BarColumn, TextColumn, PercentageColumn

console = Console()

def run_simulation():
    console.print("[bold cyan]Starting simulated task...[/bold cyan]")
    
    with Progress(
        TextColumn("[bold blue]{task.description}[/bold blu…
11 0 Open
Concurrency & performance medium

How to Implement a Token Bucket Rate Limiter with asyncio in Python

This code implements a thread-safe token bucket rate limiter for asyncio, allowing you to limit the rate of async tasks or API calls.

asyncio rate-limiting token-bucket
Python
import asyncio
import time


class TokenBucket:
    def __init__(self, rate_per_second, capacity):
        self.rate = rate_per_second
        self.capacity = capacity
        self.tokens = capacity
        self.last_refill = time.monotonic()
        self.lock = asyncio.Lock()

    async def acquire(self):
        asy…
14 0 Open
Testing & modern typing medium

How to Load Test a Local API with Locust in Python

Defines a Locust load test that simulates traffic to local endpoints, enabling manual load testing against a development server.

locust load-testing performance-testing
Python
from locust import HttpUser, task, between


class WebsiteUser(HttpUser):
    wait_time = between(1, 3)

    @task
    def home_page(self):
        self.client.get("/")

    @task(3)
    def about_page(self):
        self.client.get("/about")


if __name__ == "__main__":
    print("Run with: locust -f this_file.py --h…
16 0 Open
Testing & modern typing medium

How to Mock and Stub API Calls in Playwright E2E Tests with Python

This code demonstrates how to mock and stub API responses in Playwright end-to-end tests using Python's unittest.mock patch and Playwright's APIRequestContext.

playwright e2e-testing mocking
Python
import re
from unittest.mock import patch
from playwright.sync_api import sync_playwright

def verify_api_mock(page, mock_url, mock_response):
    with patch("playwright.sync_api.APIRequestContext.get") as mock_get:
        mock_get.return_value.json.return_value = mock_response
        mock_get.return_value.status_co…
13 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.