Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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.
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"{…
Generate a Mock Presigned URL in Python with HMAC
Build a mock AWS S3 presigned URL using an HMAC-SHA256 signature, mimicking the core SigV4 pattern without cloud SDK dependencies.
import hashlib
import hmac
import time
import base64
def generate_presigned_url_mock(secret_key, bucket, object_key, expires_in=3600):
# Build the canonical request string (simplified AWS SigV4 style)
timestamp = str(int(time.time()))
expiry = str(int(time.time()) + expires_in)
payload = f"GET\n/{buck…
How to Filter Query Parameters by Operator in Python
Parse a URL query string and keep only parameters with allowed comparison operators like eq, gt, and lt.
from urllib.parse import urlparse, parse_qs
def filter_operators(query_string, allowed=("eq", "gt", "lt")):
parsed = urlparse(query_string)
params = parse_qs(parsed.query)
filtered = {}
for key, values in params.items():
if "__" in key:
field, op = key.rsplit("__", 1)
i…
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.
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…
How to Prefix Python API URIs with a Version Slug
Build a versioned API endpoint by optionally adding a version prefix like v1 to the URL path using the stdlib urllib module.
from urllib.parse import urlparse
BASE_URL = "https://api.example.com"
def build_uri(resource, version="v1"):
"""Mock a versioned API URI with an optional v1 prefix."""
parsed = urlparse(BASE_URL)
prefix = f"/{version}" if version else ""
return f"{parsed.scheme}://{parsed.netloc}{prefix}/{resource.l…
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()
…
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…
How to Encode and Decode JWT with HS256 in Python
Implement JWT encoding and decoding using HMAC-SHA256 (HS256) with Python's standard library, including signature verification.
import base64
import hashlib
import hmac
import json
def base64url_encode(data: bytes) -> bytes:
return base64.urlsafe_b64encode(data).rstrip(b"=")
def base64url_decode(data: str) -> bytes:
padding = "=" * (-len(data) % 4)
return base64.urlsafe_b64decode(data + padding)
def encode_jwt(payload: dict, …
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…
Docker healthcheck CMD mock in Python
Runs a subprocess to curl a health endpoint and returns exit code 0 when healthy, 1 when unhealthy, mimicking a Docker HEALTHCHECK command.
import subprocess
import sys
def run_healthcheck() -> int:
result = subprocess.run(["curl", "-fsS", "http://localhost:8080/health"], capture_output=True, text=True)
if result.returncode == 0:
print("healthy")
return 0
print("unhealthy", file=sys.stderr)
return 1
if __name__ == "__ma…
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.