Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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.
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()
…
Serve Swagger UI with Python's built-in HTTP server
Hosts a self-contained Swagger UI with a mock OpenAPI spec using only Python's standard library HTTP server.
from http.server import HTTPServer, SimpleHTTPRequestHandler
import os
import tempfile
SWAGGER_HTML = """<!DOCTYPE html>
<html>
<head>
<title>Mock Swagger UI</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@4/swagger-ui.css">
</head>
<body>
<div id="swagger-ui"></div>
<script src…
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.