Reference library

Python Code Samples

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

42 matches
Strings & text easy

Extract URLs from text with regex in Python

Uses a regular expression to find and print HTTP/HTTPS URLs from a block of text.

regex url text-processing
Python
import re

text = """
Visit https://www.example.com for docs.
Contact support@mysite.org.
Check http://localhost:8000/api or ftp://files.example.net.
"""

url_pattern = r'https?://[^\s]+'

urls = re.findall(url_pattern, text)

for url in urls:
    print(url)
14 0 Open
Errors & debugging easy

How to Build an Error Code Enum in Python

Define an API error code enum with descriptions and build structured error payloads for HTTP responses.

enum error-handling api
Python
from enum import Enum

class APIErrorCode(Enum):
    SUCCESS = 0
    BAD_REQUEST = 400
    UNAUTHORIZED = 401
    FORBIDDEN = 403
    NOT_FOUND = 404
    CONFLICT = 409
    INTERNAL_ERROR = 500


def describe_error(code):
    descriptions = {
        APIErrorCode.SUCCESS: "Request completed successfully",
        APIE…
11 0 Open
Errors & debugging easy

How to Mock a Failing Dependency to Test Error Paths in Python

Inject a fake HTTP client that raises a connection error to test how code handles dependency failures without touching the network.

testing mocking requests
Python
import requests

def fetch_user(user_id):
    url = f"https://api.example.com/users/{user_id}"
    response = requests.get(url, timeout=5)
    response.raise_for_status()
    return response.json()

def get_user_name(user_id, http_client):
    try:
        user_data = http_client(user_id)
        return user_data["nam…
16 0 Open
Errors & debugging easy

Map Exception Type to HTTP Status Code in Python

Maps Python exception types to appropriate HTTP status codes using a dictionary lookup for consistent API error handling.

exceptions http-status error-handling
Python
EXCEPTION_STATUS_MAP = {
    ValueError: 400,
    KeyError: 400,
    TypeError: 400,
    PermissionError: 403,
    FileNotFoundError: 404,
    AttributeError: 404,
    TimeoutError: 408,
    NotImplementedError: 501,
    ConnectionError: 503,
}


def status_code_for(exception_type):
    try:
        return EXCEPTION_S…
13 0 Open
Files & data easy

How to Fetch Weather Data from a Public API in Python

Fetches and parses weather data from a free public API using only the Python standard library.

api json weather
Python
import urllib.request
import json

def get_weather(city):
    base_url = f"https://wttr.in/{city}?format=j1"
    with urllib.request.urlopen(base_url) as response:
        data = json.loads(response.read().decode())
    current = data["current_condition"][0]
    temp = current["temp_C"]
    desc = current["weatherDesc…
91 0 Open
OOP & classes easy

Define an Enum for Status Codes in Python

Create a readable StatusCode enum with HTTP-style status values and iterate over its members using the standard library Enum class.

enum status-codes oop
Python
from enum import Enum

class StatusCode(Enum):
    OK = 200
    CREATED = 201
    BAD_REQUEST = 400
    UNAUTHORIZED = 401
    NOT_FOUND = 404
    INTERNAL_ERROR = 500

if __name__ == "__main__":
    code = StatusCode.NOT_FOUND
    print(f"Name: {code.name}")
    print(f"Value: {code.value}")
    print(f"Is it OK? {co…
15 0 Open
Automation & scripting easy

Create a Simple HTTP File Server in Python

This code creates a simple HTTP file server that serves files from the current working directory on port 8000 using Python's built-in http.server module.

http server file-server
Python
import http.server
import socketserver
import os

PORT = 8000
DIRECTORY = os.getcwd()

class CustomHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

    def log_message(self, format, *args):
        print(f"[{self.log…
55 0 Open
Automation & scripting easy

How to Check Website Status Codes in Python

This script checks the HTTP status codes of multiple URLs concurrently using a thread pool and prints the results.

requests threading http-status
Python
import requests
from concurrent.futures import ThreadPoolExecutor

URLS = [
    "https://www.google.com",
    "https://www.python.org",
    "https://www.nonexistent-site-12345.com",
    "https://www.github.com",
]

def check_status(url):
    try:
        response = requests.get(url, timeout=5)
        return url, resp…
11 0 Open
Automation & scripting easy

How to Cross Post Markdown to dev.to API in Python

A Python function that POSTs markdown content to the dev.to API and handles HTTP or URLError exceptions with mock API testing.

api dev.to markdown
Python
import json
from urllib import request, error


def cross_post_to_devto(markdown_content, api_key, devto_api_url="https://dev.to/api/articles"):
    """
    Mock cross-posting of markdown content to the dev.to API.
    Returns the API response or an error message.
    """
    payload = json.dumps({
        "article": …
10 0 Open
Automation & scripting easy

How to generate website performance reports from HTTP requests in Python

Measure and report website load time, status code, and content size using Python's standard library.

http performance urllib
Python
import urllib.request
import time

def measure_website_load_time(url):
    """Measures total loading time of a website."""
    start_time = time.time()
    try:
        with urllib.request.urlopen(url, timeout=10) as response:
            content = response.read()
            status_code = response.status
            …
38 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

Port Scan Localhost Common Ports in Python

Scan common localhost ports (HTTP, HTTPS, SSH, FTP, and more) with a fast socket-based Python script that prints an open/closed status table.

socket port-scanning network
Python
import socket
from datetime import datetime

COMMON_PORTS = {
    80: "HTTP", 
    443: "HTTPS", 
    22: "SSH", 
    21: "FTP", 
    25: "SMTP",
    3306: "MySQL",
    5432: "PostgreSQL"
}

def scan_port(port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(0.1)
    try:
        resu…
12 0 Open
Automation & scripting easy

Post a message to a Slack webhook in Python

Send a message to a Slack webhook endpoint using the standard library's urllib.request, handling the POST request and response cleanly.

slack webhook urllib
Python
import json
from urllib import request

def post_to_slack(webhook_url: str, message: str) -> dict:
    payload = json.dumps({"text": message}).encode("utf-8")
    req = request.Request(
        webhook_url,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    wit…
10 0 Open
Cloud + Python easy

How to Mock GCP Cloud Functions HTTP Events in Python

Simulate a GCP Cloud Functions HTTP event with a Python mock handler that constructs a realistic event payload and returns a JSON response.

gcp cloud-functions mock
Python
import json
from datetime import datetime, timezone


def mock_http_event(data):
    """Simulate a GCP Cloud Function HTTP event."""
    event = {
        "event_id": "mock-event-12345",
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "event_type": "google.cloud.functions.http",
        "resource"…
13 0 Open
Concurrency & performance easy

How to Test HTTPX Async Client Pool Reuse with Mocks in Python

Mock an httpx.AsyncClient to verify connection pool reuse by asserting GET calls share a single client instance across concurrent async requests.

httpx async-await mock
Python
import asyncio
import httpx
from unittest.mock import AsyncMock, patch, Mock

async def fetch_with_pool(client, url, n_reuses=3):
    results = []
    for i in range(n_reuses):
        resp = await client.get(url)
        results.append(resp.status_code)
        await asyncio.sleep(0)  # yield to loop to mimic real us…
13 0 Open
Testing & modern typing easy

How to Mock requests.get in Python

Mock requests.get with unittest.mock to test code that makes HTTP calls without hitting the network.

mocking requests unit-testing
Python
import requests
from unittest.mock import Mock, patch

def fetch_user_data(user_id):
    response = requests.get(f"https://api.example.com/users/{user_id}")
    return response.json()

def process_user(user_id):
    mock_response = Mock()
    mock_response.json.return_value = {"id": user_id, "name": "Alice", "age": 30…
12 0 Open
API design & gRPC easy

Generate an OpenAPI Spec from Mock Routes in Python

This Python script generates an OpenAPI 3.0 specification from a simple mock routes dictionary, mapping each HTTP method to response examples.

openapi api-docs api-design
Python
import json
from pathlib import Path


def generate_openapi_spec(routes: dict, title: str = "Mock API", version: str = "1.0.0") -> dict:
    paths = {}
    for route, methods in routes.items():
        path_item = {}
        for method, response_data in methods.items():
            method = method.lower()
            …
15 0 Open
API design & gRPC easy

How to Implement Pagination with Offset and Limit in Python

A mock API pagination pattern that parses page and per_page query parameters, computes offset and limit, and slices a list of items for a specific page.

api pagination query-params
Python
def paginate(items, page, per_page):
    offset = (page - 1) * per_page
    return items[offset:offset + per_page]


def parse_query_params(query_string):
    params = {}
    if query_string:
        for pair in query_string.split("&"):
            key, value = pair.split("=")
            params[key] = value
    page …
12 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 Content-Disposition and Extract Filename in Python

Parse and mock Content-Disposition headers in Python to extract filenames, handling both plain and RFC 5987 encoded values.

http mocking regex
Python
import os
from pathlib import Path
import re
from unittest.mock import patch

def get_filename_from_content_disposition(header_value):
    """
    Extract filename from a Content-Disposition header value.
    Supports both filename and filename* parameters (RFC 5987).
    """
    if not header_value:
        return No…
15 0 Open
API design & gRPC easy

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.

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

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.

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

How to handle CORS preflight OPTIONS requests in Python

Create a mock HTTP server with a CORS preflight OPTIONS handler that returns the correct headers for browser-based API requests.

cors http server
Python
from http.server import BaseHTTPRequestHandler, HTTPServer

class CORSRequestHandler(BaseHTTPRequestHandler):
    def _send_cors_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
        self.send_head…
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.